简体   繁体   中英

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:

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

Is this possible to achieve with 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

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. Check spring documentation for more details on this class.

In your class add handleTechincalException method as below for required exceptions.

@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>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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