You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为UserDetails.getAuthorities()空指针异常创建自定义异常并返回至Postman

解决自定义异常处理器无法返回Postman响应的问题

1. 为异常处理器类添加全局注解

你的异常处理器方法仅标注了@ExceptionHandler,默认只能处理当前控制器类内的异常。要全局捕获自定义异常,需给处理器类添加@RestControllerAdvice注解(该注解包含@ResponseBody,可直接返回JSON格式响应):

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.msdev.order_controller_api.customException.UserNotExistException;

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(UserNotExistException.class)
    public ResponseEntity<String> handlerUserNotExistException(UserNotExistException exception){
        return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(exception.getMessage());
    }
}

2. 确保异常在正确时机抛出

原场景中直接调用user.getAuthorities()触发NullPointerException,需先判断user是否为null,主动抛出自定义异常,而非让JVM自动抛出NPE:

// 示例:获取UserDetails的逻辑中添加判空处理
UserDetails user = userDetailsService.loadUserByUsername(username);
if (user == null) {
    throw new UserNotExistException();
}
// 再安全调用getAuthorities
Collection<? extends GrantedAuthority> authorities = user.getAuthorities();

3. 处理Spring Security过滤器链中的异常

如果异常是在Spring Security过滤器流程中抛出(比如UserDetailsService的loadUserByUsername方法内),需配置Security的异常处理逻辑,确保异常能被正常捕获并返回响应:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            // 其他Security配置...
            .exceptionHandling(exceptions -> exceptions
                .authenticationEntryPoint((request, response, authException) -> {
                    // 针对认证阶段的用户不存在异常返回自定义响应
                    response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
                    response.setContentType("application/json");
                    response.getWriter().write("{\"message\":\"User not found\"}");
                })
            );
        return http.build();
    }
}

内容的提问来源于stack exchange,提问作者Santana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 08:20:03