I want to return HTTP status other than 200 without using the @ExceptionHandler
annotation.
The reason for this is that not every call to my application, which results in a status which is not OK should throw an exception, at least not in my opinion.
As an example, if a user is trying to log into the system, but provides an inaccurate password, I see no reason to throw an exception over this just in order to be able to return a 401 status. Instead, I would like to be able to return the status from within a "regular" method.
The reason behind this is that throwing unnecessary exceptions both clutters my log files, and "uses" my log aggregator (Rollbar/Sentry) monthly allowance.
I've tried annotating methods with @ResponseStatus
and @ResponseBody
, but it didn't work.
I looked around for blog posts or other articles on the issue but couldn't find anything.
Any idea if this is possible?
You can use RessponseEntity
. Replace the /*STATUS CODE*/
with whatever you want:
@GetMapping("/url")
@ResponseBody
public ResponseEntity<?> handlerMethod(/*parameters*/) {
// ...
return ResponseEntity.status(/*STATUS CODE*/).body(...);
}