SpringBoot 项目在Filter中抛出异常,使用@ControllerAdvice+@ExceptionHandler无法捕获,需要特殊处理,处理方法如下:
需要自己创建继一个Controller来承BasicErrorController,具体实现
package com.knight.controller;
import com.knight.response.Result;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
//因为Filter在controller之前,所以这里用来特殊处理Filter抛出的异常
@RestController
public class ErrorController extends BasicErrorController {
public ErrorController() {
super(new DefaultErrorAttributes(), new ErrorProperties());
}
@Override
@RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = getErrorAttributes(request, ErrorAttributeOptions.defaults());
Map<String, Object> result = Result.ofMap(Result.ofFail(-1, body.get("error").toString()));
/*
* 这里定义一个Map,包装好你要返回的结果即可
*/
return new ResponseEntity<>(result, HttpStatus.OK);
}
}