0

I have the following code in my web application:

@ExceptionHandler(InstanceNotFoundException.class)
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public ModelAndView instanceNotFoundException(InstanceNotFoundException e) {
        return returnErrorPage(message, e);
    }

Is it possible to also append a status message to the response? I need to add some additional semantics for my errors, like in the case of the snippet I posted I would like to append which class was the element of which the instance was not found.

Is this even possible?

EDIT: I tried this:

@ResponseStatus(value=HttpStatus.NO_CONTENT, reason="My message")

But then when I try to get this message in the client, it's not set.

      URL u = new URL ( url);
        HttpURLConnection huc =  (HttpURLConnection) u.openConnection();
        huc.setRequestMethod("GET");
        HttpURLConnection.setFollowRedirects(true);
        huc.connect();
        final int code = huc.getResponseCode();
        String message = huc.getResponseMessage();

2 Answers 2

2

Turns out I needed to activate custom messages on Tomcat using this parameter:

-Dorg.apache.coyote.USE_CUSTOM_STATUS_MSG_IN_HEADER=true
Sign up to request clarification or add additional context in comments.

1 Comment

how did you set this parameter with embedded tomcat in spring boot??
1

The message can be in the body rather than in header. Similar to a successful method, set the response (text, json, xml..) to be returned, but set the http status to an error value. I have found that to be more useful than the custom message in header. The following example shows the response with a custom header and a message in body. A ModelAndView that take to another page will also be conceptually similar.

@ExceptionHandler(InstanceNotFoundException.class)
public ResponseEntity<String> handle() {
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.set("ACustomHttpHeader", "The custom value");
    return new ResponseEntity<String>("the error message", responseHeaders, HttpStatus.INTERNAL_SERVER_ERROR);
}

2 Comments

The probem is, I need to know what caused the error without actually getting the response body.
Sure, as shown above you could just add a new header in the response and not the response body. Will work consistently across app servers and need not change the default behaviour.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.