2020年12月21日星期一

I want to return status code of 400 instead of 500 about unhandled exceptions, globally

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

https://stackoverflow.com/questions/65403092/i-want-to-return-status-code-of-400-instead-of-500-about-unhandled-exceptions-g December 22, 2020 at 11:59AM

没有评论:

发表评论