Springboot 中如何处理异常
时间: 2023-11-22 18:52:03 浏览: 32
在 Springboot 中,可以通过以下方式来处理异常:
1. 使用 @ExceptionHandler 注解处理控制器中出现的异常,例如:
```
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handleException(Exception e) {
log.error("Exception: ", e);
return Result.error("系统异常,请稍后重试!");
}
```
2. 使用 @ControllerAdvice 注解处理整个应用中出现的异常,例如:
```
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handleException(Exception e) {
log.error("Exception: ", e);
return Result.error("系统异常,请稍后重试!");
}
}
```
3. 自定义异常类,并使用 @ResponseStatus 注解指定响应状态码,例如:
```
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
public BadRequestException(String message) {
super(message);
}
}
```
在控制器方法中抛出该异常:
```
@GetMapping("/user/{id}")
public User getUser(@PathVariable Long id) {
User user = userService.getUserById(id);
if (user == null) {
throw new BadRequestException("用户不存在!");
}
return user;
}
```
以上是 Springboot 中处理异常的几种方式,开发者可以根据实际情况选择合适的方式。