在Spring Boot中的rest控制器中处理异常 [英] Handle exceptions in a rest controller in Spring Boot

查看:93
本文介绍了在Spring Boot中的rest控制器中处理异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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:


  1. 为方法签名添加例外。
    在这里,我可能依靠Spring Boot将有关异常和状态代码的所有信息传递给客户端。但是不知道这是否是一种可靠的方法。

  1. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆