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;
}
}