Spring REST by GET error 500 при несуществующем id?
Суть такова: при вызове по GET с id, которого нет в бд, падает с ошибкой 500, вместо сообщения моей кастомной ошибки. Не могу понять почему и как исправить. Спасибо!
Контроллер:
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import ru.petClinic.common.ResponseDto;
import ru.petClinic.errors.ValidateException;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("doctor")
@RequiredArgsConstructor
public class DoctorController {
private final DoctorService doctorService;
@GetMapping("{id}")
ResponseDto<DoctorResponseDto> getById(@PathVariable Long id) throws ValidateException {
log.debug("getById: started with id: {}", id);
DoctorResponseDto result = doctorService.getById(id);
log.info("getById: finished for id: {}, with result: {}", id, result);
return new ResponseDto<>(null, result);
}
Service:
import lombok.RequiredArgsConstructor;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import ru.petClinic.errors.ValidateException;
import javax.transaction.Transactional;
import java.util.List;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class DoctorService {
private final DoctorRepository doctorRepository;
private final DoctorMapper doctorMapper;
public DoctorResponseDto getById(Long id) throws ValidateException {
Doctor doctorEntity = doctorRepository.getById(id).orElseThrow(()
-> new ValidateException(String.format("Врача с таким id: %s не найдено.", id)));
return doctorMapper.fromEntity(doctorEntity);
}
ResponseDto:
import lombok.Value;
@Value
public class ResponseDto<T> {
String error;
T data;
}
MyException:
public class ValidateException extends Exception {
public ValidateException(String message) {
super(message);
}
}
Ответы (1 шт):
Автор решения: Roman Konoval
→ Ссылка
Сейчас все работает правильно - необработанное исключение это 500 ошибка. Чтобы исправить нужно добавить метод(ы) в контроллер или в отдельный бин (удобно для централизованной обработка ошибок):
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception e) {
return new ResponseEntity<String>(e.getMessage(), mapExceptionToStatus(exception.getClass()));
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleIOException(IOException ex) {
return new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
}