简体   繁体   English

在 spring 启动 api 中使用自定义 json 响应创建自定义异常

[英]Create custom exception with custom json response in spring boot api

I would like to throw different exceptions with different Strings (giving details of the error via message) with a very specific JSON structure, something like:我想用非常具体的 JSON 结构用不同的字符串(通过消息提供错误的详细信息)抛出不同的异常,例如:

   [
      {
        "error": [
          {
            "statusCode": 400,
            "customMessage": "xxx",
            "timestamp": "time"
          }
        ]
      }
    ]

Is this possible to achieve with Spring Boot?这可以通过 Spring Boot 实现吗? I haven't found how to do it.我还没有找到怎么做。

You can implement an Error Handler.您可以实现错误处理程序。 You can follow this one: https://github.com/olein/Java-AWS-RnD/blob/main/src/main/java/com/rnd/aws/controller/ErrorHandler.java你可以关注这个: https://github.com/olein/Java-AWS-RnD/blob/main/src/main/java/com/rnd/aws/controller/ErrorHandler.java

You can throw exception with some code or error message and prepare your response there.您可以使用一些代码或错误消息引发异常,并在那里准备您的响应。

Create an ErrorHandler(as per your naming convention) class and extend spring class ResponseEntityExceptionHandler which receives all method exceptions.创建一个 ErrorHandler(根据您的命名约定) class 并扩展 spring class ResponseEntityExceptionHandler 接收所有方法异常。 Check spring documentation for more details on this class.有关此 class 的更多详细信息,请查看 spring 文档。

In your class add handleTechincalException method as below for required exceptions.在您的 class 添加 handleTechincalException 方法如下所需的异常。

@ExceptionHandler({ Exception.class, AbcException.class, XyzException.class })
public ResponseEntity<Object> handleTechnicalException(Exception e, WebRequest webRequest) {
// prepare response entity object as required based on type of exception 
// return ResponseEntity<Object>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM