天天看点

自定义异常+全局异常处理

1、自定义异常

public class MyException extends RuntimeException {
    private static final long serialVersionUID = -1;
    @Getter
    @Setter
    private String errorCode;
    /**
     * 异常处理类
     * @param errorCode 错误码
     * @param message   错误信息
     */
    public MyException (final String errorCode, final String message) {
        super(message);
        this.errorCode = errorCode;
    }
}
           

2、全局异常处理类

一、@ControllerAdvice顾名思义就是controller的增强器,@ControllerAdvice注解将作用在所有注解了@RequestMapping的控制器的方法上。(如果全部异常处理返回json,那么可以使用 @RestControllerAdvice 代替 @ControllerAdvice ,这样在方法上就可以不需要添加 @ResponseBody。)

二、@ExceptionHandler:用于全局处理控制器里的异常。

@Slf4j
@ControllerAdvice
@RestController
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public Map defaultErrorHandler(HttpServletRequest req, Exception e) {
        log.error("ERROR RequestURL: {}, errorMessage: \n{} ", req.getRequestURL(), e);
        Map<String, String> map = new HashMap<>(1);
        if (e instanceof MyException ) {
            //业务异常
            String errorCode = ((MyException ) e).getErrorCode();
            map.put("code", errorCode);
            map.put("message", e.getMessage());
            return map;
        } else {
            map.put("code", "500000");
            map.put("message", "系统内部错误");
        }
        log.error("errorCode:{}, message:{}", map.get("code"), e.getMessage(), e);
        return map;
    }
}