Home > Software engineering >  Create custom exception with custom json response in spring boot api
Create custom exception with custom json response in spring boot api

Time:01-04

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.

CodePudding user response:

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.

CodePudding user response:

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>
}
  •  Tags:  
  • Related