如何在Spring Boot中捕获JwtAuthFilter中的异常并使用全局错误处理程序处理?

huangapple go评论53阅读模式
英文:

How do I catch exceptions in JwtAuthFilter and handle with Global Error Handler in Spring Boot?

问题

以下是您提供的内容的翻译:

"标题" 中提到,我正在探讨作为请求的一部分验证接收到的JWT,并且我正在努力找出如何捕获JWT身份验证过滤器和全局错误处理程序中引发的相关异常,并在全局错误处理程序中处理它们,因为我很欣赏那里的格式。

到目前为止,我尝试在JWT身份验证过滤器和JWT服务中捕获异常,但错误处理程序似乎无法捕获它们,我已经意识到这是因为过滤器与控制器和服务是分离的层,而错误处理程序会在控制器和服务中找到异常。我已经尝试了在Stack Overflow 和视频教程中找到的内容,但没有成功。

如果您可以指向一个可见的示例,以便我可以看到如何正确地执行它,那将非常感激。请让我知道如果我没有提供足够的信息。以下是我认为的最新状态的相关类(SecurityConfig、JwtAuthFilter、JwtService、GlobalErrorHandler)。请原谅混乱,因为我在过去的两周里一直在尝试找到有效的解决方案。非常感谢您的任何帮助。

SecurityConfig

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final JwtAuthFilter authFilter;

    private final UserDetailsService userDetailsService;

    private final UserAuthenticationEntryPoint userAuthenticationEntryPoint;

    // ... 省略了一些配置

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // ... 省略了一些配置
        return http
            .exceptionHandling().authenticationEntryPoint(userAuthenticationEntryPoint)
            // ... 省略了一些配置
            .build();
    }

    // ... 省略了一些配置
}

JwtAuthFilter

@Component
@RequiredArgsConstructor
public class JwtAuthFilter extends OncePerRequestFilter {

    private final JwtService jwtService;
    private final OwnerRepository ownerRepository;

    @Override
    protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response,
                                    @NotNull FilterChain filterChain)
            throws ServletException, IOException {
        try {
            // ... 省略了一些过滤逻辑
        } catch (ExpiredJwtException e) {
            // ... 省略了一些处理逻辑
        }
        filterChain.doFilter(request, response);
    }

    // ... 省略了一些配置
}

JwtService

@Service
public class JwtService {

    // ... 省略了一些配置

    // 创建令牌
    private String buildToken(String username) {
        // ... 省略了一些令牌创建逻辑
        return token;
    }

    public String generateToken(String username) {
        return buildToken(username);
    }

    // ... 省略了一些配置

    // 验证令牌
    public boolean isTokenValid(String token, UserDetails userDetails) {
        // ... 省略了一些验证逻辑
        return (username.equals(userDetails.getUsername())) && !isTokenExpired(token);
    }

    public void validateToken(String token, UserDetails userDetails) {
        // ... 省略了一些验证逻辑
    }

    // ... 省略了一些配置
}

GlobalErrorHandler

@Data
@RestControllerAdvice
public class GlobalErrorHandler {

    private String message;

    private enum LogStatus {
        STACK_TRACE, MESSAGE_ONLY
    }

    @ExceptionHandler(NumberFormatException.class)
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    public Map<String, Object> handleNumberFormatException(
            NumberFormatException e, WebRequest webRequest) {
        return createExceptionMessage(e.getLocalizedMessage(), HttpStatus.BAD_REQUEST, webRequest);
    }

    // ... 省略了一些异常处理方法

    private Map<String, Object> createExceptionMessage(String e, HttpStatus status, WebRequest webRequest) {
        Map<String, Object> error = new HashMap<>();
        String timestamp = ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME);

        if (webRequest instanceof ServletWebRequest) {
            error.put("uri",
                    ((ServletWebRequest) webRequest).getRequest().getRequestURI());
        }
        error.put("message", e);
        error.put("status code", status.value());
        error.put("timestamp", timestamp);
        error.put("reason", status.getReasonPhrase());
        return error;
    }
}

请注意,以上代码是您提供的代码的翻译,没有进行其他修改。如果您需要进一步的帮助或有任何问题,请随时提问。

英文:

As the title states, I am exploring validating recieved jwts as part of a request but I am struggling to figure out how to catch related exceptions thrown in my JWT auth filter and handle them with a global error handler as I appreciate the formatting there.

So far I've tried catching the exceptions in the jwt auth filter and jwt service without the error handler being able to pick them up and have come to realize it seems the handler wont because the filter is a seperate layer from the controllers and services which is where the error handler finds exceptions. I've tried incorporating what I have been able to find on stack overflow and video tutorials so far but without success.

Any help would be greatly appreciated, especially if you can point me to a visible example so I can see how it is done properly and specifically. Please let me know if I have not provided enough information. The following are what I believe are the relevant classes in their latest state(SecurityConfig, JwtAuthFilter, JwtService, GlobalErrorHandler ). Please forgive the mess as I have been all over the place the last two weeks trying to find something that works. Any help is greatly appreciated.

SecurityConfig

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final JwtAuthFilter authFilter;

    private final UserDetailsService userDetailsService;

    private final UserAuthenticationEntryPoint userAuthenticationEntryPoint;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        System.out.println(&quot;filter chain&quot;);
            return
                    http
                            .exceptionHandling().authenticationEntryPoint(userAuthenticationEntryPoint)
                            .and()
                            .addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class)
                            .csrf().disable()

//                whitelisted
                            .authorizeHttpRequests()
                            .requestMatchers(&quot;/api/menu/**&quot;, &quot;/api/order/**&quot;, &quot;/api/owners-tools/login&quot;).permitAll()
                            .and()
//               restricted
                            .authorizeHttpRequests().requestMatchers(&quot;/api/owners-tools/**&quot;)
                            .authenticated().and()
                            .sessionManagement()
                            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                            .and()
                            .authenticationProvider(authenticationProvider())
//                            .addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class)
                            .build();
    }

    @Bean
    public  PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationProvider authenticationProvider(){
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        return daoAuthenticationProvider;
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config)throws Exception{
        return config.getAuthenticationManager();
    }
}

JwtAuthFilter

@Component
@RequiredArgsConstructor
public class JwtAuthFilter extends OncePerRequestFilter {

    private final JwtService jwtService;
    private final OwnerRepository ownerRepository;



    @Override
    protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response,
                                    @NotNull FilterChain filterChain)
            throws ServletException, IOException {


try {
            String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
            String token = null;
            String username = null;
            Date expiration = null;
            Date issuedAt = null;
//        String passwrd = null;
//        System.out.println(authHeader);
            if (authHeader != null &amp;&amp; authHeader.startsWith(&quot;Bearer &quot;)) {
                token = authHeader.substring(7);
//            System.out.println(&quot;token = &quot; + token);
                username = jwtService.extractUsername(token);
//            System.out.println(&quot;username = &quot; + username);
                expiration = jwtService.extractExpiration(token);
                System.out.println(&quot;expiration = &quot; + expiration);
                issuedAt = jwtService.extractIssuedAt(token);
                System.out.println(&quot;issued at = &quot; + issuedAt);
            }

        assert expiration != null;
        if (!issuedAt.before(expiration)){
            throw new JwtException(&quot;invalid date&quot;) ;
        }
            if (username != null &amp;&amp; SecurityContextHolder.getContext().getAuthentication() == null) {
                System.out.println(&quot;encypted username: &quot; + username);
                System.out.println(&quot;decrypted : &quot; + jwtService.decrypt(username));
                UserDetails userDetails = userDetailsService().loadUserByUsername(jwtService.decrypt(username));
                if (userDetails == null) {
                    throw new UsernameNotFoundException(&quot;Invalid user&quot;);
                }
                System.out.println(&quot;token valid: &quot; + jwtService.isTokenValid(token, userDetails));
                //           UserDetails userDetails = userDetailsService().loadUserByUsername(username);
                jwtService.validateToken(token, userDetails);
                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userDetails, null
                        , userDetails.getAuthorities());
                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authToken);
                System.out.println(&quot;jwt filter&quot;);
//                filterChain.doFilter(request, response);
            }
//        filterChain.doFilter(request, response);
        }catch (ExpiredJwtException e){
            System.out.println(e.getLocalizedMessage());
            response.setContentType(&quot;application/json&quot;);
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getOutputStream().println(&quot;{ \&quot;error\&quot;: \&quot;token issued after expiration\&quot; }&quot;);
//    response.getOutputStream().println(&quot;{error:&quot; +  e.getMessage()  + &quot;}&quot;);
    response.getOutputStream().println(e.getLocalizedMessage());
//            throw new ExpiredJwtException(e.getHeader(), e.getClaims(), &quot;expired&quot; );
//    ResponseWrapper responseWrapper = new ResponseWrapper().fail().msg(e.getMessage());
        }
        filterChain.doFilter(request, response);
    }
//            throws ServletException, IOException {
//        String authHeader = request.getHeader(&quot;Authorization&quot;);
//        String token = null;
//        String username = null;
////        String passwrd = null;
////        System.out.println(authHeader);
//        if (authHeader!=null &amp;&amp; authHeader.startsWith(&quot;Bearer &quot;)){
//            token = authHeader.substring(7);
////            System.out.println(&quot;token = &quot; + token);
//            username = jwtService.extractUsername(token);
////            System.out.println(&quot;username = &quot; + username);
//        }
//        if (username != null &amp;&amp; SecurityContextHolder.getContext().getAuthentication()==null){
//            UserDetails userDetails = userDetailsService().loadUserByUsername(jwtService.decrypt(username));
//            if (userDetails == null){
//                throw new UsernameNotFoundException(&quot;Invalid user&quot;);
//            }
//            //           UserDetails userDetails = userDetailsService().loadUserByUsername(username);
//            jwtService.validateToken(token, userDetails);
//            UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userDetails, null
//                    , userDetails.getAuthorities());
//            authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
//            SecurityContextHolder.getContext().setAuthentication(authToken);
//            System.out.println(&quot;jwt filter&quot;);
//        }
//        filterChain.doFilter(request, response);
//    }

    @Bean
    UserDetailsService userDetailsService(){
        return username -&gt; ownerRepository.findByUsername(username)
                .orElseThrow(() -&gt; new UsernameNotFoundException(&quot;Username invalid.&quot;));
    }
}


JwtService

@Service
public class JwtService {
//create token
@Value(&quot;${key}&quot;)
private String SECRET;
@Value(&quot;${BEGIN_KEY}&quot;)
private int BEGIN_KEY;
@Value(&quot;${END_KEY}&quot;)
private int END_KEY;
@Value(&quot;${charmin}&quot;)
private int charmin;
@Value(&quot;${charmax}&quot;)
private int charmax;
@Value(&quot;${submin}&quot;)
private int submin;
@Value(&quot;${submax}&quot;)
private int submax;
@Value(&quot;${ex1}&quot;)
private int ex1;
@Value(&quot;${ex2}&quot;)
private int ex2;
@Value(&quot;${ex3}&quot;)
private int ex3;
@Value(&quot;${CHARSET}&quot;)
private String CHARSET;
private Key getSignKey(){
byte[] keyBytes = Decoders.BASE64.decode(SECRET);
return Keys.hmacShaKeyFor(keyBytes);
}
private String buildToken(String username){
//        set time variable instead of creating new
String token = Jwts.builder()
.setSubject(username)
.setIssuedAt(new Date(System.currentTimeMillis()))
//                16 hours, reflective of our owners work day - to be altered to facilitate mitigation of token capture
.setExpiration(new Date(System.currentTimeMillis() + (1000 * 60 * 60) * 16))
.signWith(getSignKey(), SignatureAlgorithm.HS256).compact();
System.out.println(token);
System.out.println(&quot;token issued: &quot; + new Date(System.currentTimeMillis()));
System.out.println(&quot;token expires: &quot; + new Date(System.currentTimeMillis() + (1000 * 60 * 60) * 16));
//        try {
//            return token;
//        }catch (io.jsonwebtoken.security.SignatureException exception){
//            System.out.println(exception.getLocalizedMessage());
//        }
return token;
}
public String generateToken(String username){
return buildToken(username);
}
//    validate token
private Claims extractAllClaims(String token){
//        try {
//            return
//                    Jwts
//                            .parserBuilder()
//                            .setSigningKey(getSignKey())
//                            .build()
//                            .parseClaimsJws(token)
//                            .getBody();
//        } catch (ExpiredJwtException e) {
//            System.out.println(e.getLocalizedMessage());
//            throw new JwtException(&quot;bad jwt&quot;);
//        }
return
Jwts
.parserBuilder()
.setSigningKey(getSignKey())
.build()
.parseClaimsJws(token)
.getBody();
}
public &lt;T&gt; T extractClaim(String token, Function&lt;Claims, T&gt; claimsResolver){
final Claims claims = extractAllClaims(token);
return claimsResolver.apply(claims);
}
public String extractUsername(String token){
return extractClaim(token, Claims::getSubject);
}
public Date extractExpiration(String token){
return extractClaim(token, Claims::getExpiration);
}
public Date extractIssuedAt(String token){
return extractClaim(token, Claims::getIssuedAt);
}
private Boolean isTokenExpired(String token){
return extractExpiration(token).before(new Date());
}
//    possibly condense into one
public boolean isTokenValid(String token, UserDetails userDetails) {
final String username = decrypt(extractUsername(token));
//        if (!username.equals(userDetails.getUsername()) &amp;&amp; isTokenExpired(token)){
//            throw new SignatureException(&quot;token no good&quot;);
//        }
return (username.equals(userDetails.getUsername())) &amp;&amp; !isTokenExpired(token);
}
//    public void validateToken(String token, UserDetails userDetails){
//        final String username = extractUsername(token);
//        userDetails.getUsername();
//    }
public void validateToken(String token, UserDetails userDetails){
final String username = extractUsername(token);
userDetails.getUsername();
}
//  encrypt - used during development as a means to encrypt credentials
//  before storing them and facilitating decryption means
public String encrypt(String string){
//        rework
System.out.println(&quot;value to be encrypted: &quot; + string);
byte[] codeBytes = string.getBytes(StandardCharsets.UTF_8);
List&lt;Integer&gt; rolledCodeBytes = new ArrayList&lt;&gt;();
int codeByteValue;
//        System.out.println(&quot;begin key: &quot; + BEGIN_KEY);
//        System.out.println(&quot;code bytes &quot; + Arrays.toString(codeBytes));
for (byte codeByte : codeBytes) {
codeByteValue = codeByte;
//            System.out.println(codeByteValue += BEGIN_KEY);
//            System.out.println(&quot;key &quot; + BEGIN_KEY);
codeByteValue += BEGIN_KEY;
rolledCodeBytes.add(codeByteValue);
}
//        System.out.println(&quot;rolled code bytes: &quot; + rolledCodeBytes);
//      new collection with altered char values
List&lt;Character&gt; chars = new ArrayList&lt;&gt;();
for (int integer : rolledCodeBytes) {
chars.add((char) integer);
}
//      convert chars to string
//        StringBuilder rolledCharBuilder = new StringBuilder(chars.size());
//        for (Character ch : chars) {
//            rolledCharBuilder.append(ch);
//        }
//        System.out.println(&quot;chars: &quot; + chars);
//        System.out.println(&quot;rolled charbuilder: &quot; + rolledCharBuilder);
//      for each element insert three new random chars
for (int i = 0; i &lt; chars.size(); i++) {
chars.add(i, randomChar());
i++;
chars.add(i, randomChar());
i++;
chars.add(i, randomChar());
i++;
}
chars.add(randomChar());
chars.add(randomChar());
chars.add(randomChar());
//        -----------------------------------
StringBuilder encryptionBuilder = new StringBuilder(chars.size());
for (Character ch : chars) {
encryptionBuilder.append(ch);
}
System.out.println(&quot;value encrypted: &quot; + encryptionBuilder);
return encryptionBuilder.toString();
}
//    decrypt
public String decrypt(String  encodedString)  {
String decodedStart = String.valueOf(encodedString.charAt(BEGIN_KEY));
String decodedEnd = String.valueOf(encodedString.charAt(encodedString.length() - END_KEY));
String wholeDecoded = &quot;&quot;;
StringBuilder decoded = new StringBuilder();
for (int i = BEGIN_KEY; i &lt; encodedString.length(); i = i + END_KEY) {
decoded.append(encodedString.charAt(i));
}
decoded = new StringBuilder(decoded.substring(submin, decoded.toString().length() - submax));
wholeDecoded = wholeDecoded.concat(decodedStart + decoded + decodedEnd);
byte[] decodedBytes = wholeDecoded.getBytes(StandardCharsets.UTF_8);
int decodeByteValue;
List&lt;Character&gt; decodedChars = new ArrayList&lt;&gt;();
StringBuilder decrypt = new StringBuilder(0);
for (byte codeByte : decodedBytes) {
decodeByteValue = codeByte;
decodeByteValue -= BEGIN_KEY;
decodedChars.add((char) decodeByteValue);
}
for (Character ch : decodedChars) {
decrypt.append(ch);
}
return decrypt.toString();
}
private char randomChar() {
int min = charmin, max = charmax;
int random = (int) (Math.random() * ((max - min)) + min);
int[] excluded = {ex1, ex2, ex3};
char choice = 0;
for (int ex : excluded) {
choice = random == ex ? randomChar() : (char) random;
}
return choice;
}
}

GlobalErrorHandler

@Data
@RestControllerAdvice
public class GlobalErrorHandler{
private String message;
private enum LogStatus{
STACK_TRACE, MESSAGE_ONLY
}
@ExceptionHandler(NumberFormatException.class)
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
public Map &lt;String, Object&gt; handleNumberFormatException(
NumberFormatException e, WebRequest webRequest){
return createExceptionMessage(e.getLocalizedMessage(), HttpStatus.BAD_REQUEST, webRequest);
}
@ExceptionHandler(EntityNotFoundException.class)
@ResponseStatus(code = HttpStatus.NOT_FOUND)
public Map &lt;String, Object&gt; handleEntityNotFoundException(
EntityNotFoundException e, WebRequest webRequest) {
return createExceptionMessage(e.getLocalizedMessage(), HttpStatus.NOT_FOUND, webRequest);
}
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
public Map &lt;String, Object&gt; handleIllegalArgumentException(
IllegalArgumentException e, WebRequest webRequest){
return createExceptionMessage(e.getLocalizedMessage(), HttpStatus.BAD_REQUEST, webRequest);
}
@ExceptionHandler(UsernameNotFoundException.class)
@ResponseStatus(code = HttpStatus.FORBIDDEN)
public Map&lt;String, Object&gt; handleUsernameNotFoundException(
UsernameNotFoundException e, WebRequest webRequest){
return  createExceptionMessage(e.getLocalizedMessage(), HttpStatus.FORBIDDEN, webRequest);
}
@ExceptionHandler(SignatureException.class)
@ResponseStatus(code = HttpStatus.FORBIDDEN)
public Map&lt;String, Object&gt; handleSignatureException(
SignatureException e, WebRequest webRequest){
return  createExceptionMessage(e.getLocalizedMessage(), HttpStatus.FORBIDDEN, webRequest);
}
@ExceptionHandler(JwtException.class)
@ResponseStatus(code = HttpStatus.FORBIDDEN)
public Map&lt;String, Object&gt; handleJwtException(
JwtException e, WebRequest webRequest){
return  createExceptionMessage(e.getLocalizedMessage(), HttpStatus.FORBIDDEN, webRequest);
}
@ExceptionHandler(MalformedJwtException.class)
@ResponseStatus(code = HttpStatus.FORBIDDEN)
public Map&lt;String, Object&gt; handleMalformedJwtException(
MalformedJwtException e, WebRequest webRequest){
return  createExceptionMessage(e.getLocalizedMessage(), HttpStatus.FORBIDDEN, webRequest);
}
@ExceptionHandler(ExpiredJwtException.class)
@ResponseStatus(code = HttpStatus.FORBIDDEN)
public Map&lt;String, Object&gt; handleExpiredJwtException(
ExpiredJwtException e, WebRequest webRequest){
return  createExceptionMessage(e.getMessage(), HttpStatus.FORBIDDEN, webRequest);
}
@ExceptionHandler(BadCredentialsException.class)
@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
public Map&lt;String, Object&gt; handleBadCredentialsException(
BadCredentialsException e, WebRequest webRequest
){
return createExceptionMessage(e.getLocalizedMessage(), HttpStatus.UNAUTHORIZED, webRequest);
}
//    ---------------- Being reworked
// alter to not just create the message but also log the error
// create method to log the error to an internal file
private Map&lt;String,Object&gt; createExceptionMessage(String e, HttpStatus status, WebRequest webRequest) {
Map &lt;String, Object&gt; error = new HashMap&lt;&gt;();
String timestamp = ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME);
if(webRequest instanceof ServletWebRequest){
error.put(&quot;uri&quot;,
((ServletWebRequest)webRequest).getRequest().getRequestURI());
}
error.put(&quot;message&quot;, e);
error.put(&quot;status code&quot;, status.value());
error.put(&quot;timestamp&quot;, timestamp);
error.put(&quot;reason&quot;, status.getReasonPhrase());
return error;
}
}

答案1

得分: 0

你的全局错误处理程序不会捕获在过滤器级别抛出的异常。
您可以将HandlerExceptionResolver注入到您的过滤器中,然后在出现异常的情况下使用resolveException方法。
这里有一个类似的问题:https://stackoverflow.com/questions/34595605/how-to-manage-exceptions-thrown-in-filters-in-spring。

我认为您正在寻找的是第二个答案(重用使用@RestControllerAdvice注解标记的GlobalExceptionHandler)。

这是一个示例:

@Component
@RequiredArgsConstructor
public class JwtAuthFilter extends OncePerRequestFilter {

    private final JwtService jwtService;
    private final OwnerRepository ownerRepository;
    private final HandlerExceptionResolver resolver;

    @Override
    protected void doFilterInternal(HttpServletRequest request, @NotNullHttpServletResponse response,
                                    @NotNull FilterChain filterChain)
                                    throws ServletException, IOException {
        try {
            // 逻辑
        } catch (Exception e) {
            resolver.resolveException(request, response, null, e);
        }
    }
}

希望这对您有帮助。

英文:

Your global error handler wont catch exceptions thrown at filter level.
You can inject a HandlerExceptionResolver into your filter, and then in case of an exception use the resolveException method.
There's a similar question here https://stackoverflow.com/questions/34595605/how-to-manage-exceptions-thrown-in-filters-in-spring.

The second answer is the one I think youre looking for (reusing the GlobalExceptionHandler annotated with @RestControllerAdvice).

And here's an example:

@Component
@RequiredArgsConstructor
public class JwtAuthFilter extends OncePerRequestFilter {
private final JwtService jwtService;
private final OwnerRepository ownerRepository;
private final HandlerExceptionResolver resolver;
@Override
protected void doFilterInternal(HttpServletRequest request, @NotNullHttpServletResponse response,
@NotNull FilterChain filterChain)
throws ServletException, IOException {
try{
//logic
} catch (Exception e){
resolver.resolveException(request, response, null, e);
}
}

Hope that works

huangapple
  • 本文由 发表于 2023年6月2日 10:22:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76386768.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定