SpringBoot全局异常处理

自定义异常信息

/**
 * Description: 业务异常提示信息枚举类
 *
 * @Date: 2020/3/13 11:37
 * @Author: wangbo
 */
public enum BusinessMsgEnum {

    /**
     * 参数异常
     */
    PARMETER_EXCEPTION("102", "参数异常!"),
    /**
     * 等待超时
     */
    SERVICE_TIME_OUT("103", "服务调用超时!"),
    /**
     * 参数过大
     */
    PARMETER_BIG_EXCEPTION("102", "输入的金额不大于1亿!"),
    /**
     * 500 : 一劳永逸的提示也可以在这定义
     */
    UNEXPECTED_EXCEPTION("500", "系统发生异常,请联系管理员!");
    // 还可以定义更多的业务异常

    /**
     * 消息码
     */
    private String code;
    /**
     * 消息内容
     */
    private String msg;

    private BusinessMsgEnum(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }
    // 省略get set方法
}

自定义业务异常

public class BusinessErrorException extends RuntimeException {
    private static final long serialVersionUID = -7480022450501760611L;

    /**
     * 异常码
     */
    private String code;
    /**
     * 异常提示信息
     */
    private String message;

    public BusinessErrorException(BusinessMsgEnum businessMsgEnum) {
        this.code = businessMsgEnum.getCode();
        this.message = businessMsgEnum.getMsg();
    }
    // 省略get set

创建全局异常处理GlobalExceptionHandler

/**
 * @ControllerAdvice 注解
 * 1、包含了 @Component 注解,说明在 Spring Boot 启动时,
 * 也会把该类作为组件交给 Spring 来管理。
 * 2、该注解还有个 basePackages 属性,该属性是用来拦截哪个
 * 包中的异常信息,一般我们不指定这个属性,我们拦截项目工程
 * 中的所有异常
 * @ExceptionHandler 指定处理哪些异常
 * @ResponseStatus 看源码就知道了,是一个枚举类
 */

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    // 打印log
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理缺少请求参数异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public JsonResult handleHttpMessageNotReadableException(
            MissingServletRequestParameterException ex) {
        logger.error("缺少请求参数,{}", ex.getMessage());
        return new JsonResult("400", "缺少必要的请求参数");
    }

    /**
     * 空指针异常
     *
     * @param ex NullPointerException
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public JsonResult handleTypeMismatchException(NullPointerException ex) {
        logger.error("空指针异常,{}", ex.getMessage());
        return new JsonResult("500", "空指针异常了");
    }

    /**
     * 系统异常 预期以外异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public JsonResult handleUnexpectedServer(Exception ex) {
        logger.error("系统异常:", ex);
        return new JsonResult("500", "系统发生异常,请联系管理员");
    }

    /**
     * 拦截业务异常,返回业务异常信息
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(BusinessErrorException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public JsonResult handleBusinessError(BusinessErrorException ex) {
        String code = ex.getCode();
        String message = ex.getMessage();
        return new JsonResult(code, message);
    }
}

测试

@RestController
@RequestMapping("/exception")
public class ExceptionController {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionController.class);
    /**
     * 测试缺少参数
     * @param name
     * @param pass
     * @return
     */
    @PostMapping("/test")
    public JsonResult test(@RequestParam(value = "name", required = true) String name,
                           @RequestParam(value = "pass", required = true) String pass) {
        logger.info("name:{}", name);
        logger.info("pass:{}", pass);
        return new JsonResult();
    }
    /**
     * 测试自定义业务异常
     * @return
     */
    @GetMapping("/business")
    public JsonResult testException() {
        try {
            int i = 1 / 0;
        } catch (Exception e) {
            throw new BusinessErrorException(BusinessMsgEnum.UNEXPECTED_EXCEPTION);
        }
        return new JsonResult();
    }
}

你可能感兴趣的:(SpringBoot,spring,boot)