Home > Back-end >  Spring @RestControllerAdvice doesn't handle status code 400 exceptions
Spring @RestControllerAdvice doesn't handle status code 400 exceptions

Time:07-08

I have the following class for handling rest controller exceptions

@RestControllerAdvice
class RestResponseEntityExceptionHandler : ResponseEntityExceptionHandler() {
    @ExceptionHandler(
        value = [
            (NotFoundException::class),
            (AccountNotFoundException::class),
            (ExecutionLogNotFoundException::class),
            (SubscriptionNotFoundException::class)
        ]
    )
    protected fun notFoundException(
        ex: Throwable?,
        request: WebRequest?
    ): ResponseEntity<ErrorsDetails> {
        val errorDetails = ErrorsDetails(
            ex?.message!!
        )
        return ResponseEntity(errorDetails, HttpStatus.NOT_FOUND)
    }

    @ExceptionHandler(
        value = [
            (AccountIsNotConnectedException::class),
            (AccountCannotBeDeletedException::class),
            (InvalidVerificationSignatureException::class),
            (SubscriptionAlreadyExistsException::class),
            (ConstraintViolationException::class)
        ]
    )
    protected fun badRequestException(
        ex: Throwable?,
        request: WebRequest?
    ): ResponseEntity<ErrorsDetails> {
        val errorDetails = ErrorsDetails(
            ex?.message!!
        )
        return ResponseEntity(errorDetails, HttpStatus.BAD_REQUEST)
    }
}

And while all status code 404 exceptions pass through notFoundException with no problems, when a status code 400 exception is thrown badRequestException is never entered. Can you help me understand what the problem here is and how to fix it?

CodePudding user response:

You are capturing these exceptions to be handled as 400 exceptions:

        (AccountIsNotConnectedException::class),
        (AccountCannotBeDeletedException::class),
        (InvalidVerificationSignatureException::class),
        (SubscriptionAlreadyExistsException::class),
        (ConstraintViolationException::class)

However, maybe these are not the exceptions that are being thrown. Check the logs for the exceptions that you throw on your code. Probably you will need to add other exceptions here.

  • Related