我需要在我的全局异常处理器中处理 NoHandlerFoundException
异常情况。
在此之前,我已经通过扩展 ResponseEntityExceptionHandler
类并覆写方法,实现了对 MethodArgumentNotValidException
的处理,以此来管理请求体中缺失字段的问题。
但目前,在运行应用程序时,遇到了以下异常状况。
我原本利用 MethodArgumentNotValidException
处理器来应对请求体中字段缺失的情形。
Caused by: org.springframework.beans.BeanInstantiationException:
Failed to instantiate
[org.springframework.web.servlet.HandlerExceptionResolver]: Factory
method 'handlerExceptionResolver' threw exception with message:
Ambiguous @ExceptionHandler method mapped for [class
org.springframework.web.bind.MethodArgumentNotValidException]:
{protected org.springframework.http.ResponseEntity
com.kroger.iwt.coreservice.exception.handler.GlobalExceptionHandler.handleMethodArgumentNotValid(org.springframework.web.bind.MethodArgumentNotValidException,org.springframework.http.HttpHeaders,org.springframework.http.HttpStatusCode,org.springframework.web.context.request.WebRequest),
public final org.springframework.http.ResponseEntity
org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(java.lang.Exception,org.springframework.web.context.request.WebRequest)
throws java.lang.Exception}
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({ NoHandlerFoundException.class })
@ResponseBody
@ResponseStatus(HttpStatus.NOT_FOUND)
public ResponseEntity<ErrorListResponse> notFound(final NoHandlerFoundException exception) {
log.error("{} {}", 404, exception.getMessage());
ErrorListResponse errorListResponse = errorResponse("Request URI Not Found", exception);
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorListResponse);
}
// @Override
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
List<FieldError> errors = ex.getBindingResult().getFieldErrors();
List<ErrorListResponse.ErrorDetails> errorDetails = new ArrayList<>();
for (FieldError fieldError : errors) {
ErrorListResponse.ErrorDetails error = new ErrorListResponse.ErrorDetails();
error.setReason(fieldError.getDefaultMessage());
error.setCode("BAD_REQUEST");
error.setDatetime(new DateTimeResponse(Instant.now().toString(), "America/New_York"));
errorDetails.add(error);
}
ErrorListResponse errorResponse = new ErrorListResponse();
errorResponse.setErrors(errorDetails);
log.error("{} {}", 400, "Multiple fields are invalid");
return new ResponseEntity(errorResponse, HttpStatus.BAD_REQUEST);
}
}