将HttpStatus代码自定义到列不能为null



当我有java.sql.SQLIntegrityConstraintViolationException: Column 'xpto' cannot be null时,在Rest-Api上返回的最佳HttpStatus代码是什么?

我有一个其他类型的异常处理程序,但不能为空字段:

@ExceptionHandler({DataIntegrityViolationException.class})
protected ResponseEntity<Object> handleDataIntegrityViolation(DataIntegrityViolationException ex, WebRequest request) {
Throwable cause = ex.getRootCause();
if (cause instanceof SQLIntegrityConstraintViolationException) {
SQLIntegrityConstraintViolationException consEx = (SQLIntegrityConstraintViolationException)cause;
String message = "";
String constraint = "";
HttpStatus httpStatus = null;
if (consEx.getMessage().contains("UNIQUE")) {
message = "Cannot enter the same record twice";
constraint = "DUPLICATED_RECORD";
httpStatus = HttpStatus.CONFLICT;
} else if (consEx.getMessage().contains("foreign key constraint")) {
message = "Record still have reference from other table";
constraint = "USED_RECORD";
httpStatus = HttpStatus.UNPROCESSABLE_ENTITY;
}
return this.buildResponseEntity(new ApiError(httpStatus, message, consEx.getMessage(), constraint));
} else {
return ex.getCause() instanceof org.hibernate.exception.ConstraintViolationException ? this.buildResponseEntity(new ApiError(HttpStatus.CONFLICT, "Database error", ex)) : this.buildResponseEntity(new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, ex));
}
}

我为column cannot be null添加了一个处理方法,并使用400-BAD_REQUEST作为http状态代码:

@ExceptionHandler(DataIntegrityViolationException.class)
protected ResponseEntity<Object> handleDataIntegrityViolation(DataIntegrityViolationException ex,
WebRequest request) {
Throwable cause = ex.getRootCause();
if (cause instanceof SQLIntegrityConstraintViolationException) {
SQLIntegrityConstraintViolationException consEx = (SQLIntegrityConstraintViolationException) cause;
String message = "";
String constraint = "";
HttpStatus httpStatus = null;
if (consEx.getMessage().contains("UNIQUE")) {
message = "Cannot enter the same record twice";
constraint = "DUPLICATED_RECORD";
httpStatus = HttpStatus.CONFLICT;
} else if (consEx.getMessage().contains("foreign key constraint")) {
message = "Record still have reference from other table";
constraint = "USED_RECORD";
httpStatus = HttpStatus.UNPROCESSABLE_ENTITY;
} else if (consEx.getMessage().contains("cannot be null")){
message = "Record cannot be null";
constraint = "NULL_RECORD";
httpStatus = BAD_REQUEST;
}
return buildResponseEntity(new ApiError(httpStatus, message, consEx.getMessage(), constraint));
} else if (ex.getCause() instanceof ConstraintViolationException) {
return buildResponseEntity(new ApiError(HttpStatus.CONFLICT, "Database error", ex));
}
return buildResponseEntity(new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, ex));
}

相关内容

  • 没有找到相关文章

最新更新