-1

I am trying to make 500 Internal Server Error to 400 Bad Request in every cases.

This is my package structure for exceptions.

Directory image

For example, ConflictExeption looks like this.

@ResponseStatus(HttpStatus.CONFLICT)
public class ConflictException extends ApiException {
    public ConflictException(String message) {
        super(message);
    }

    public ConflictException() {
        this("Conflict Exception.");
    }
}
public class ApiException extends RuntimeException {
    public ApiException(String message) {
        super(message);
    }
}
public class UserEmailInUseException extends ConflictException{

    public static final String MESSAGE = "Desired email is already in use.";

    public UserEmailInUseException() {
        super(MESSAGE);
    }
}

Below is my simple service code.


@Service
public class UsersService {
    @Transactional
        public UserInfoResponseDto signUp(UserSignupRequestDto requestDto) {
            if (usersRepository.findByEmail(requestDto.getEmail()).isPresent()) throw new 
                UserEmailInUseException();
        return new UserInfoResponseDto(usersRepository.save(requestDto.toEntity()));

    }

}

UserEmailInUseException extends ConflictException.

In my case, 500 error occurs when some violations are made while making transaction with MariaDB.

Simply put, I just want to return status code of 400 instead of 500, where exception is not handled.

Thanks in advance!

Also, I've tried this example below, and it seems to send 500.. Link

Roy Ra
  • 504
  • 1
  • 6
  • 23
  • I've thought about covering each method in service codes with try-catch block, but personally I think this will make my code really dirty,. – Roy Ra Dec 22 '20 at 04:05
  • You showed BadRequestException but you present code using UserEmailInUseException and ConflictException that have no source that makes it harder to answer. – Aleksander Lech Dec 22 '20 at 04:05
  • @AleksanderLech Done! – Roy Ra Dec 22 '20 at 04:08
  • Doing this probably a bad idea. You should be fixing your server code so it avoids or handles exceptions properly. – Raedwald Dec 22 '20 at 10:34

2 Answers2

0

Have you tried:

@RestControllerAdvice
public class RestErrorHandler {

    @ExceptionHandler
    @ResponseStatus(BAD_REQUEST)
    Exception handleUnhandledException(Exception e) {
        return e;
    }
}
Vertigo
  • 107
  • 7
0

First of all you are mapping it to CONFLICT instead of BAD_REQUEST. Have you tried the following annotation setting?

@ResponseStatus(HttpStatus.BAD_REQUEST)

If you don't want to change existing ConflictException try to introduce a new base exception as follows:

@ResponseStatus(HttpStatus.BAD_REQUEST)
public class BadRequestException extends ApiException {
    // [...]
}
Aleksander Lech
  • 1,105
  • 12
  • 16