iamjoshua
iamjoshua

Reputation: 1269

How to disable Spring boots default error handling?

I already tried disabling the Default Error handling of Spring boot w/c throws

{ "timestamp": 1575346220347, "status": 500, "error": "Internal Server Error", "exception": "org.springframework.web.client.HttpClientErrorException", "message": "401 Unauthorized", "path": "/auth/login" }

By adding the ff. Config.

   @SpringBootApplication(exclude = ErrorMvcAutoConfiguration.class)

and

spring.autoconfigure.exclude: org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration

But I'm getting a bunch of HTML formatted Response instead of the JSON response it should be getting from the server.

Upvotes: 2

Views: 7374

Answers (2)

iamjoshua
iamjoshua

Reputation: 1269

I was not able to disable SpringBoots automatic handling of Error responses however I was able to get the proper JSON Error Response by wrapping my Rest Template request in a try catch and using a library in the rest template as it turns out there is a bug in Rest Template that wouldn't allow me to retrieve the Response body.

From

private final RestTemplate restTemplate = new RestTemplate();

To

private final RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());

Try-Catch Wrapping

 ResponseEntity resp = null;

try{
            resp = restTemplate.postForEntity(hostUrl+loginUrl, request,Object.class);
        }catch(HttpClientErrorException e)  {
            ErrorDto result = new ObjectMapper().readValue(e.getResponseBodyAsString(), ErrorDto.class);                
            return new ResponseEntity<>(result, e.getStatusCode());
        }

ErrorDto.java

@JsonIgnoreProperties(ignoreUnknown = true)
public class ErrorDto {

    @JsonProperty("Message")
    private String message;
    @JsonProperty("Reason")
    private String reason;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }
}

Upvotes: 0

rifat sahariar
rifat sahariar

Reputation: 53

You can Use Controller Advice to make a global exception handler. Inside the ControllerAdvice class, you can use @ExceptionHandler annotation to handle exceptions. Here is a good article about ControllerAdvice. https://medium.com/@jovannypcg/understanding-springs-controlleradvice-cd96a364033f

Upvotes: 2

Related Questions