Return HTTP code 200 from Spring REST API

Peter Penzov :

I want to use this code to receive http link with values:

@PostMapping(value = "/v1/notification")
public String handleNotifications(@RequestParam("notification") String itemid) {
    // parse here the values
    return "result successful result";
}

How I can return http code 200 - successful response?

And also for example if there is a code exception into code processing how can I return error 404?

lealceldeiro :

You can do it by annotating your method with @ResponseStatus using HttpStatus.OK (However it should be 200 by default), like this:

Some controller

@PostMapping(value = "/v1/notification")
@ResponseStatus(HttpStatus.OK)
public String handleNotifications(@RequestParam("notification") String itemid) throws MyException {
    if(someCondition) {
       throw new MyException("some message");
    }
    // parse here the values
    return "result successful result";
}

Now, in order to return a custom code when handling a specific exception you can create a whole separate controller for doing this (you can do it in the same controller, though) which extends from ResponseEntityExceptionHandler and is annotated with @RestControllerAdvice and it must have a method for handling that specific exception as shown below:

Exception handling controller

@RestControllerAdvice
public class ExceptionHandlerController extends ResponseEntityExceptionHandler {

    @ExceptionHandler(MyException.class)
    protected ResponseEntity<Object> handleMyException(MyException ex, WebRequest req) {
        Object resBody = "some message";
        return handleExceptionInternal(ex, resBody, new HttpHeaders(), HttpStatus.NOT_FOUND, req);
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=71734&siteId=1