java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringMVC @ExceptionHandler用法

SpringMVC @ExceptionHandler典型用法及说明

作者:张紫娃

文章介绍了Spring中的异常处理机制,包括处理单个和多个异常类型的方法,返回结构化错误信息的推荐做法,以及处理所有异常的兜底方法,另外,还提到了@ExceptionHandler方法的多种返回类型

处理单个异常类型

当 getUser() 方法抛出 UserNotFoundException 时,会自动调用 handleUserNotFound() 方法进行处理。

@RestController
@RequestMapping("/users")
public class UserController {

    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        // 可能抛出 UserNotFoundException
        return userService.getUserById(id);
    }

    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<String> handleUserNotFound(UserNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
    }
}

处理多个异常类型

一个 @ExceptionHandler 方法可以处理多个异常类型:

@ExceptionHandler({IllegalArgumentException.class, ResourceNotFoundException.class})
public ResponseEntity<String> handleClientErrors(RuntimeException ex) {
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("客户端错误: " + ex.getMessage());
}

结合 @ResponseStatus 使用(返回指定状态码)

此时返回值直接作为响应体,HTTP 状态码由 @ResponseStatus 指定。

@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleResourceNotFound(ResourceNotFoundException ex) {
    return ex.getMessage();
}

返回结构化错误信息(推荐做法)

@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<ErrorResponse> handleUserNotFound(UserNotFoundException ex) {
    ErrorResponse error = new ErrorResponse(HttpStatus.NOT_FOUND.value(), ex.getMessage(), LocalDateTime.now());
    return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
}

// ErrorResponse 示例类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ErrorResponse {
    private int status;
    private String message;
    private LocalDateTime timestamp;
}

捕获所有异常(兜底处理)

注意顺序:

更具体的异常应放在前面,避免被 Exception.class 拦截。

@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorResponse handleAllExceptions(Exception ex) {
    return new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系统内部错误", ex.getMessage(), LocalDateTime.now());
}

不同返回类型

@ExceptionHandler 方法可以有多种返回类型,如 String, ResponseEntity, Map, 自定义 DTO 等。

@RestController
@RequestMapping("/users")
public class UserController {

    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("用户 ID 不合法");
        }
        // ...
    }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handleIllegalArgument(IllegalArgumentException ex) {
        return "参数错误:" + ex.getMessage();
    }

    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleUserNotFound(UserNotFoundException ex) {
        ErrorResponse error = new ErrorResponse(404, ex.getMessage(), LocalDateTime.now());
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorResponse handleAllExceptions(Exception ex) {
        return new ErrorResponse(500, "系统错误", ex.getMessage(), LocalDateTime.now());
    }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文