spring boot 項目在Filter中拋出異常,使用@ControllerAdvice+@ExceptionHandler無法處理,處理方法如下:
自己創建Controller繼承BasicErrorController,具體實現
@RestController @Api(value = "filter錯誤處理", description = "filter錯誤處理") public class ErrorController extends BasicErrorController { public ErrorController() { super(new DefaultErrorAttributes(), new ErrorProperties()); } @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) { Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL)); HttpStatus status = getStatus(request); //自定義的錯誤信息類 //status.value():錯誤代碼, //body.get("message").toString()錯誤信息 R ret = R.error(status.value(), body.get("message").toString()); //TokenException Filter拋出的自定義錯誤類 if (!Strings.isNullOrEmpty((String) body.get("exception")) && body.get("exception").equals(TokenException.class.getName())) { body.put("status", HttpStatus.FORBIDDEN.value()); status = HttpStatus.FORBIDDEN; } return new ResponseEntity<Map<String, Object>>(ret, status); } @Override public String getErrorPath() { return "error/error"; } }