通常,我们通过 @ControllerAdvice 和 @ExceptionHandler 来捕获并处理 Controller 层面的异常。但是,filter 是在 controller 层之前的,需要先通过 filter 才能到达 controller 层,此文就介绍一下如何捕获filter层面的异常。
Spring 的异常会转发到 BasicErrorController
中进行异常写入,然后才会返回客户端。所以,我们可以在 BasicErrorController
对 filter
异常进行捕获并处理。
所以,我们需要重写BasicErrorController
中的error
方法。
import com.ddky.mobile.vo.basicVO.ResponseVO; import org.springframework.boot.autoconfigure.web.ServerProperties; 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中异常返回值问题 * @author : lzb * @date: 2022-05-10 09:16 */ @RestController public class FilterErrorController extends BasicErrorController { public FilterErrorController(ServerProperties serverProperties) { super(new DefaultErrorAttributes(), serverProperties.getError()); } @Override @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity error(HttpServletRequest request) { Map<String, Object> body = getErrorAttributes(request, ErrorAttributeOptions.defaults()); //可以通过断点调试来查看body中的信息 HttpStatus status = getStatus(request); ResponseVO response = new ResponseVO(); response.setCode(status.value()); response.setMessage(String.valueOf(body.get("error"))); return new ResponseEntity<>(response,status); } }
此处,ResponseVO
是我自定义的一个通用返回器,如果用 ResponseEntity
直接返回也是可以的。自定义通用返回器可以配合 SpringMVC 的配置来更正确地实现。
补充:下面介绍下spring boot 如何捕获filter抛出的异常,自定义返回结构
主要是继承 BasicErrorController
@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, isIncludeStackTrace(request, MediaType.ALL)); HttpStatus status = getStatus(request); Map<String, Object> map = new HashMap<>(); map.put("message", "error"); return new ResponseEntity<Map<String, Object>>(map, status); } }
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)