user11058144
user11058144

Reputation: 177

How to I make sure that throwing a HttpClientErrorException causes an HTTP 400 response?

When I throw a HttpClientErrorException, I was expecting the HTTP Code to be HTTP 400 based on the sample code below. Instead, I get an HTTP 500 response code with the message 400 BAD_REQUEST.

import org.springframework.http.HttpStatus;

*****

    @CrossOrigin
    @RequestMapping(value = *****************, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "", notes = "Does Stuff")
    public DTO save(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        ******
        try {
            if (isError) {
                handleSaveError(HttpStatus.BAD_REQUEST, "It was your fault, fix it.");
            } else {
                **** Success ****
            }
        } catch (IllegalStateException | IOException e) {
            handleSaveError(HttpStatus.INTERNAL_SERVER_ERROR, "It was my fault, call back later.");
        }
        return dto;
    }

    private void handleSaveError(HttpStatus httpStatus, String responseMessage) {
        String body = getResponseBody(responseMessage);
        if (httpStatus.is4xxClientError()) {
            log.debug(responseMessage);
            throw new HttpClientErrorException(httpStatus, httpStatus.name(), body.getBytes(UTF_8), UTF_8);
        }
        if (httpStatus.is5xxServerError()) {
            log.error(responseMessage);
            throw new HttpServerErrorException(httpStatus, httpStatus.name(), body.getBytes(UTF_8), UTF_8);
        }
    }

Upvotes: 1

Views: 1338

Answers (3)

user11058144
user11058144

Reputation: 177

Using the information on the link provided by Spasoje Petronijević, I created a handler method in a ControllerAdvice class, and captured a custom exception class.

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import stuff.exception.RequestException;

@ControllerAdvice
public class HTTPExceptionHandler {

    @ExceptionHandler({ RequestException.class })
    public ResponseEntity<String> handleBadRequestException(RequestException ex, HttpServletRequest request) {
        return ResponseEntity
                .status(ex.getHttpStatus())
                .body(ex.getBody());
    }
}

Upvotes: 0

Suraj
Suraj

Reputation: 767

Refer https://github.com/s2agrahari/global-excpetion-handler-spring-boot creating global handler for spring boot rest service

Upvotes: 1

Spasoje Petronijević
Spasoje Petronijević

Reputation: 1598

Take a look here how you can map your Exception to appropriate status code. https://www.baeldung.com/exception-handling-for-rest-with-spring

Upvotes: 2

Related Questions