0

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?

Mahozad
  • 18,032
  • 13
  • 118
  • 133
  • Use `HttpServletResponse.setStatus` – jAC Jul 22 '18 at 14:19
  • The exception for unauth will still be created and bubble from somewhere within the Spring Security framework. Could always just turn off the logging for certain packages that are creating noise? – Darren Forsythe Jul 22 '18 at 14:20
  • Check this post [SO: Is it ok to send 200 ok with error body](https://stackoverflow.com/questions/27921537/returning-http-200-ok-with-error-within-response-body#27922900) – Aman Verma Jul 23 '18 at 03:48

2 Answers2

0

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(...);
}
Mahozad
  • 18,032
  • 13
  • 118
  • 133
0

Have a look at the following example

@RestController
public class HelloWorldController {

    @GetMapping("/hello")
    public ResponseEntity<String> sayHello() {

        return ResponseEntity.status(HttpStatus.CREATED).body("Hello World!");

    }
 }
rieckpil
  • 10,470
  • 3
  • 32
  • 56