spring boot 項目在Filter中拋出異常捕獲不到的處理方法


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM