【发布时间】:2021-12-05 22:19:49
【问题描述】:
我在一个单独的模块中创建了一个自定义异常句柄,并希望在另一个模块中使用相同的 GlobalExceptionHandle 类。虽然控制台上出现异常,但是邮递员上没有出现自定义异常。这可能是什么原因?请帮助我
GlobalExceptionHandle.java
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandle extends ResponseEntityExceptionHandler {
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<CustomExceptionResponseDto> handle(NotFoundException exception) {
return new ResponseEntity<CustomExceptionResponseDto>(
CustomExceptionResponseDto.builder()
.errorCode(HttpStatus.NOT_FOUND)
.message(exception.getMessage())
.status(HttpStatus.NOT_FOUND.value())
.timestamp(LocalDateTime.now())
.build(), HttpStatus.NOT_FOUND
);
}
@ExceptionHandler(InvalidStateException.class)
public ResponseEntity<CustomExceptionResponseDto> handle(InvalidStateException exception) {
return new ResponseEntity<CustomExceptionResponseDto>(
CustomExceptionResponseDto.builder()
.errorCode(HttpStatus.BAD_REQUEST)
.message(exception.getMessage())
.status(HttpStatus.BAD_REQUEST.value())
.timestamp(LocalDateTime.now())
.build(), HttpStatus.BAD_REQUEST
);
}
}
UserController.java
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
private final UserService userService;
@PostMapping
public ResponseEntity<UserResponseDto> save(@RequestBody UserRequestDto userRequestDto) {
return ResponseEntity.ok(userService.save(userRequestDto));
}
}
UserServiceImpl.java
@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
private final UserMapper userMapper;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
public UserResponseDto save(UserRequestDto userRequestDto) {
log.info("User request dto: " + userRequestDto);
userRepository.findUserByEmail(userRequestDto.getEmail()).ifPresent((user) -> {
throw new EmailAlreadyUseException(user.getEmail());
});
var user = userMapper.userRequestDtoToUser(userRequestDto);
user.setPassword(bCryptPasswordEncoder.encode(userRequestDto.getPassword()));
return userMapper.userToUserResponseDto(userRepository.save(user));
}
}
InvalidStateException.java
public class InvalidStateException extends RuntimeException {
private static final long serialVersionUID = 1L;
public InvalidStateException(String message) {
super(message);
}
}
EmailAlreadyUseException.java
public class EmailAlreadyUseException extends InvalidStateException {
public EmailAlreadyUseException(String email) {
super(email+" already registered,try different email");
}
}
【问题讨论】:
标签: java spring-boot exception