I have a Spring endpoint for my REST web services app that I want to return a string:
"Unauthorized: token is invalid"
But my javascript on the front-end chokes on this:
JSON.parse("Unauthorized: token is invalid") //Unexpected token U
How do I get my app to return a valid JSON string? Here is my current code:
@RequestMapping(value="/401")
public ResponseEntity<String> unauthorized() {
return new ResponseEntity<String>("Unauthorized: token is invalid", HttpStatus.UNAUTHORIZED);
}
Return a Map instead.
Map<String,String> result = new HashMap<String,String>();
result.put("message", "Unauthorized...");
return result;
You don't need to return a ResponseEntity
, you can directly return a POJO or collection. Add @ResponseBody
to your handler method if you want to return a POJO or collection.
Also, I'd say it's better to use forward
over redirect
for errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With