我正在开发一个Spring Boot应用程序。我想知道处理异常的最佳方法是什么。以下是我的代码:
ExceptionHandler.java
我正在使用@ControllerAdvice
。什么是最好的选择?@ControllerAdvice
还是@RestControllerAdvice
?
(译注:@ControllerAdvice适用于返回页面,@RestControllerAdvice适用于返回JSON数据)
@ControllerAdvice
public class ExceptionHandler {
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<ErrorResponse> notFound(NotFoundException notFoundException) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.NOT_FOUND, notFoundException.getMessage());
return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.NOT_FOUND);
}
}
并且实现了服务层@Service
如下:
@Override
public User update(User newUser) throws NotFoundException {
Optional<User> user = userRepository.findById(newUser.getId());
if (!user.isPresent()) throw new NotFoundException("Record Not Found!");
return userRepository.save(newUser);
}
在Controller.java
中,代码如下:
@PutMapping
public User update(@RequestBody User user) {
User updatedUser = userService.update(user);
if (updatedUser == null) throw new SomeOtherException("Exception while Updating!");
return updatedUser;
}
我的问题是:
上述方式是否不好?在服务层中抛出异常可以吗?它会被@controlleradvice
自动捕获吗?还是只需在控制器中抛出异常?我正在寻求处理异常的最佳实践。