在Spring Boot中的rest控制器中处理异常 [英] Handle exceptions in a rest controller in Spring Boot
问题描述
我使用Spring Boot创建REST Web服务。
我想知道在控制器中处理异常的更好的方法是什么。我看过其他问题,但没有找到答案。
I create REST web-service with Spring Boot. I would like to know what is a better way to handle exceptions in a controller. I have seen other questions and didn’t found an answer.
我的控制器:
@GetMapping
public ResponseEntity<?> saveMyUser(){
MyUser myUser = new MyUser("Anna");
//throws SQLException
MyUserDetails userDetails = userService.saveMyUser(myUser);
//if successful
return ResponseBody.ok(userDetails);
}
UserService的saveMyUser()方法:
saveMyUser() method of UserService:
public MyUserDetails saveUser(MyUser) throws SQLException {...}
因此,在这一点上,我至少有两个简单的选择:
So at this point I have at least 2 simple options:
-
为方法签名添加例外。
在这里,我可能依靠Spring Boot将有关异常和状态代码的所有信息传递给客户端。但是不知道这是否是一种可靠的方法。
Add exception to method signature. Here I may rely on Spring Boot to pass all information about exception and status code to a client. However do not know if it is a reliable approach.
使用try / catch环绕并手动传递有关异常的所有信息。
Surround with try/catch and pass all information about exceptions manually.
有什么更好的简单方法?
What is a better simple way?
推荐答案
您可以使用 @ControllerAdivce
注释创建一个附加类,然后再添加一个您将能够为每个异常编写自定义响应逻辑,例如:
You can create an additional class with @ControllerAdivce
annotation and later you will be able to write custom response logic for each exception e.g:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler({SQLException.class})
public ResponseEntity<Object> sqlError(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Some SQL exception occured");
}
}
此外,您可以扩展 ResponseEntityExceptionHandler ,并覆盖从异常到HTTP响应的映射的默认行为。
Also, you can extend ResponseEntityExceptionHandler and override the default behavior for mapping from exceptions to HTTP response.
另外,请查看此,它可为您的案件提供非常有用的信息。
Also, take a look at this, it holds very usefull information for your case.
这篇关于在Spring Boot中的rest控制器中处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!