详解Spring Security 捕获 filter 层面异常返回我们自定义的内容

网友投稿 344 2022-07-31


通常,我们通过 @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 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> error(HttpServletRequest request) {

Map body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));

HttpStatus status = getStatus(request);

Map map = new HashMap<>();

map.put("message", "error");

return new ResponseEntity>(map, status);

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:SpringBoot使用spring.config.import多种方式导入配置文件(springboot引入配置文件变量)
下一篇:Java中synchronized的几种使用方法(java synchronized)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~