您可以尝试以下任何一种实现,它对我有用。您将必须重写另一种方法ResponseEntityExceptionHandler
或通过使用ExceptionHandler
.
1.通过重写ResponseEntityExceptionHandler的方法
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(CustomExceptionHandler.class);
//Other Handlers
// Handle 400 Bad Request Exceptions
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
log.info(ex.getLocalizedMessage() + " ",ex);
final CustomErrorMessage errorMessage = new CustomErrorMessage(ex.getLocalizedMessage(), InfoType.ERROR, HttpStatus.BAD_REQUEST, ex.fillInStackTrace().toString());
return handleExceptionInternal(ex, errorMessage, headers, errorMessage.getStatus(), request);
}
//Other Handlers
}
除了上面的实现之外,如果您只想在请求负载中存在无法识别的属性或空属性并且存在空值时抛出错误(如下所示),您还可以尝试下面的实现JSON
{
"":""
}
2. 使用异常处理程序
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class GenericExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GenericExceptionHandler.class);
@ExceptionHandler(value = {UnrecognizedPropertyException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
protected ResponseEntity<Object> handleUnrecognizedPropertyException(UnrecognizedPropertyException ex) {
log.info(ex.getLocalizedMessage() + " ",ex);
final String error = "JSON parse error: Unrecognized field " + "[ " + ex.getPropertyName() + " ]";
final CustomErrorMessage errorMessage = new CustomErrorMessage(error, InfoType.ERROR, HttpStatus.BAD_REQUEST);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorMessage);
}
}
Note :为了使上述两个实现正常工作,您需要在您的application.properties
file.
spring.jackson.deserialization.fail-on-unknown-properties=true
希望对你有帮助 :)