spring boot 全局异常处理通过实现 handlerexceptionresolver 接口或添加 @controlleradvice 注解的类来捕获角色分配异常。具体做法是定义一个自定义异常类(如 roleassignmentexception),并在服务层抛出该异常,然后在控制器通知类中编写 @exceptionhandler 方法来拦截并返回统一的错误响应。

如何定义角色分配异常类
首先需要创建一个继承自 RuntimeException 的自定义异常类,用于标识角色分配过程中的特定错误。这个类通常包含一个错误码和一个描述信息,以便前端能够区分不同的错误类型。

public class RoleAssignmentException extends RuntimeException {
private final String errorCode;
public RoleAssignmentException(String message, String errorCode) {
super(message);
this.errorCode = errorCode;
}
public String getErrorCode() {
return errorCode;
}
}
在业务逻辑中,当检测到用户没有权限分配角色或角色不存在时,直接抛出此异常。例如,在 UserServiceImpl 中:
public void assignRole(Long userId, Long roleId) {
if (roleId == null) {
throw new RoleAssignmentException("Role ID cannot be null", "ROLE_NULL");
}
// 其他业务逻辑...
}
如何配置全局异常处理器
接下来,创建一个带有 @RestControllerAdvice 注解的配置类,在其中使用 @ExceptionHandler 注解来指定处理 RoleAssignmentException 的方法。该方法应返回一个符合 RESTful 规范的 JSON 响应对象。

@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RoleAssignmentException.class)
public ResponseEntity<ErrorResponse> handleRoleAssignmentException(RoleAssignmentException ex) {
ErrorResponse error = new ErrorResponse(ex.getErrorCode(), ex.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);
}
}
class ErrorResponse {
private String code;
private String message;
public ErrorResponse(String code, String message) {
this.code = code;
this.message = message;
}
// getters and setters
}
这样,当 assignRole 方法抛出 RoleAssignmentException 时,Spring Boot 会自动将其捕获并通过 GlobalExceptionHandler 返回标准化的错误信息。开发者只需确保在业务代码中正确抛出异常,即可实现统一的全局异常处理。
当角色ID为null时的具体行为是什么
当传入的角色ID为 null 时,根据上述代码逻辑,系统会立即抛出 RoleAssignmentException,错误码为 ROLE_NULL,消息为 "Role ID cannot be null"。全局异常处理器捕获到该异常后,将返回 HTTP 状态码 400 Bad Request,响应体为 {"code":"ROLE_NULL","message":"Role ID cannot be null"}。这一过程不会执行后续的角色分配逻辑,确保了数据的一致性和安全性。


















