Вы можете использовать аннотации Spring * ControllerAdvice
и ExceptionHandler
для обработки исключений в вашем приложении. Приведенный ниже код возвращает 500 кодов состояния http, если в вашем запросе возникло исключение. Вы можете добавить другие классы исключений или свой собственный класс для обработки конкретных случаев и возврата клиенту определенных кодов состояния.
Редактировать
Обработка каждого кода не будет хорошей идеей. Скорее вы можете обернуть их в свое собственное исключение и предоставить правильное сообщение в службу поддержки клиентов. Тем не менее, вы можете попробовать что-то вроде ниже.
@Component
@ControllerAdvice
public class MyExceptionHandler {
@ExceptionHandler(HttpClientErrorException.BadRequest.class)
@ResponseStatus(code=HttpStatus.BAD_REQUEST, reason="Bad Request", value=HttpStatus.BAD_REQUEST)
public void handleBadRequest(HttpClientErrorException.BadRequest e) {
//handle bad request exception
}
@ExceptionHandler(HttpClientErrorException.NotFound.class)
@ResponseStatus(code=HttpStatus.NOT_FOUND, reason="Not Found", value=HttpStatus.NOT_FOUND)
public void handleNotFound(HttpClientErrorException.NotFound e) {
//handle Not Found
}
@ExceptionHandler(HttpServerErrorException.InternalServerError.class)
@ResponseStatus(code=HttpStatus.INTERNAL_SERVER_ERROR, reason="Internal Server Error", value=HttpStatus.INTERNAL_SERVER_ERROR)
public void handleInternalServerError(HttpServerErrorException.InternalServerError e) {
//handle internal server error
}
//more methods for each code.
}
Затем обработайте коды из вашего шаблона отдыха, как показано ниже. Здесь вы не сможете вернуть тело ответа клиенту.
@Component
public class LoginErrorHandler
implements ResponseErrorHandler {
@Override
public boolean hasError(ClientHttpResponse httpResponse)
throws IOException {
return (httpResponse.getStatusCode() != HttpStatus.OK);
}
@Override
public void handleError(ClientHttpResponse httpResponse)
throws IOException {
if (httpResponse.getRawStatusCode() >=400 && httpResponse.getRawStatusCode()<500 ) {
throw HttpClientErrorException.create(httpResponse.getStatusCode(), httpResponse.getStatusText(), httpResponse.getHeaders(), null, null);
}else if(httpResponse.getRawStatusCode() >=500){
throw HttpServerErrorException.create(httpResponse.getStatusCode(), httpResponse.getStatusText(), httpResponse.getHeaders(), null, null);
}else {
//throw some other exceptions for other codes and catch them in controller advice.
}
}
}