0

I am working on developing RESTful service on Java using Spring framework. If exception occurs in my services layer i throw an exception bound to Http status code. For example when user's authentication fails i send response with 401 status code.

return new ResponseEntity<>(HttpStatus.valueOf(statusCode));

I would like to explain to RESTful service consumer what is wrong with his request sending not only the code but also textual explanation. I can do this either by adding custom message to response body or by replacing default response phrase. For example replace Unauthorized for 401 with User does not exist or Incorrect password.

The problem is HttpStatus from org.springframework.http is enum and error codes are bound to textual response phrases.

Can i somehow override those response phrases or i need another approach?

And is it good practice to replace default response phrase or it would be better to put explanation message to response body?

Kirill
  • 6,762
  • 4
  • 51
  • 81
  • I tried to use `HttpServletResponse`, there is `setStatus(int sc, String sm)` method, but unfortunately it does not work as i expect and it is also deprecated. When i try to use it, it does not change default response phrase for existing code and does not add any message to my custom code, ie 488. It is advised to use `sendError(int sc, String msg)`, but it also does not change reponse phrase. It only inserts specified message to servlet container's default html error page :( – Kirill Mar 30 '16 at 13:11

1 Answers1

0

This should work:

First you can bound the request method to the type it produces by adding produces = {MediaType.TEXT_PLAIN} to your @RequestMapping where MediaType is from import javax.ws.rs.core.MediaType this will produce text plain response.

Then you can return the following: return new ResponseEntity<>(message, HttpStatus.UNAUTHORIZED); where message is the text message you want to show.

Hellzzar
  • 185
  • 1
  • 9
  • This will add message to reponse body, not header. – Kirill Mar 30 '16 at 13:14
  • I did not notice you wanted as a header. ResponseEntity constructor can have HttpHeaders as you can see in the [API](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html) but I don't think is a good practice to override HTTP code message since HTTP is an standard. I would do what I pointed to you or I would define a new header which your application could read and show: HttpHeaders myHeaders = new HttpHeaders(); myHeaders.set("MyResponseHeader", "MyValue"); return new ResponseEntity<>("", myHeaders, HttpStatus.UNAUTHORIZED); – Hellzzar Mar 30 '16 at 13:19