類上配置@RestControllerAdvice
註解,用於全局異常處理與攔截
1.正確示例
①
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public ApiResponse handleException(Exception e) {
return ApiResponse.serverError();
}
②
@ExceptionHandler(RuntimeException.class)
public ApiResponse handleSubsidiaryCheckInconsistencyException(RuntimeException exception, HttpServletResponse response) {
response.setStatus(500);
return ApiResponse.serverError();
}
2.錯誤示例
@ExceptionHandler(RuntimeException.class)
public ApiResponse handleSubsidiaryCheckInconsistencyException(RuntimeException exception, HttpServletResponse response) {
response.setStatus(10010);
return ApiResponse.serverError();
}
說明:response.setStatus
設置的狀態碼最好是規定的HttpStatus,自定義狀態碼太大,如10010
,前端無法解析,並提示如下信息
Error: Parse Error: Response overflow