CatDev
CatDev

Reputation: 43

How can I modify default Json error response Spring?

When an item that doesn't exist in my web app is invoked through an URL, Spring responds with a JSON with data like (timestand, status, error, message, path). So, I need to change the structure of this JSON, specificly I need to remove path. How can I do it? Where should I implement the customization of the exception in my project? Best regards to everyone!

Json response to modify

Upvotes: 0

Views: 945

Answers (2)

androberz
androberz

Reputation: 934

It's pretty easy in Spring MVC applications to handle errors by their types using the @ContollerAdvice class. You could define your own handler for the exceptions you get on a method calls. E.g.:

@ControllerAdvice
public class ErrorHandler {
    @ExceptionHandler(value = ExceptionToHandle.class)
    @ResponseBody
    public YourResponse handle(ExceptionToHandle ex) {
        return new YourResponse(ex.getMessage());
    }
}

Here YourResponse is just a POJO, that could have any structure your want to be presented at the client. The @ExceptionHandler specifies what types of errors will be handled in the method (including more specific types). The @ResponseBody says that your returned value will be presented in the JSON format in your response.

Upvotes: 2

pzd
pzd

Reputation: 31

You may try something like that:

@RestController
@RequestMapping("/")
public class TestController {

    @GetMapping("/exception")
    void getException() {
        throw new MyCustomException("Something went wrong!");
    }

    class MyCustomException extends RuntimeException {
        MyCustomException(String message) {
            super(message);
        }
    }

    class CustomError {
        private String message;
        private Integer code;

        CustomError(String message, Integer code) {
            this.message = message;
            this.code = code;
        }

        public String getMessage() {
            return message;
        }

        public Integer getCode() {
            return code;
        }
    }

    @ExceptionHandler(MyCustomException.class)
    public CustomError handleMyCustomException(Exception ex) {
        return new CustomError("Oops! " + ex.getMessage(), HttpStatus.BAD_REQUEST.value());
    }
}

Fast and simple, you can just make your own exception and your own error object (which is later turned to json).

If you ask where to put such a thing... Well, you can make a separate class for the exception (and an exception package also), and put a small @ExceptionHandler method inside your controller. If you don't want it to be in the same class, you may delegate it to separate class also; for further and in-depth reading, look up for annotation like @ControllerAdvice.

Upvotes: 0

Related Questions