我的要求是,如果post请求的JSON无效,我将需要发送400个HTTP响应代码,如果任何字段不可解析,返回状态代码将为422。例如,post请求可以是:
{
"amount": "12.3343",
"timestamp": "2018-07-17T09:59:51.312Z"
}
Dto类提供如下:,
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class TransactionDto {
@NotNull
@Min(0)
private BigDecimal amount;
@NotNull
private LocalDateTime timestamp;
}
这是发出POST请求的控制器,
@Slf4j
@RestController
@RequestMapping("/")
@Validated
public class TransactionController {
@Autowired
private TransactionService transactionService;
@Operation(description = "create a transaction using the provided JSON data")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Create transaction", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = Transaction.class))}),
@ApiResponse(responseCode = "204", description = "Transaction is older than 60 seconds", content = @Content(mediaType = "application/json")),
@ApiResponse(responseCode = "500", description = MessageConstant.INTERNAL_SERVER_ERROR_MSG, content = @Content)})
@PostMapping(value = "/transactions")
public ResponseEntity<Object> createProperty(@RequestBody @Valid TransactionDto transactionDto) {
try {
final LocalDateTime transactionTimestamp = transactionDto.getTimestamp();
final LocalDateTime localDateTimeNow = LocalDateTime.now(ZoneOffset.UTC);
final long secondsDuration = Duration.between(transactionTimestamp, localDateTimeNow).toSeconds();
final boolean isFuture = transactionTimestamp.isAfter(localDateTimeNow);
if (isFuture) {
return new ResponseEntity<>(ApiResponseMessage.getGenericApiResponse(Boolean.FALSE, HttpStatus.UNPROCESSABLE_ENTITY,
"Transaction is in future"), new HttpHeaders(), HttpStatus.ACCEPTED);
}
if (secondsDuration > 60) {
return new ResponseEntity<>(ApiResponseMessage.getGenericApiResponse(Boolean.FALSE, HttpStatus.NO_CONTENT,
"Transaction is older than 60 seconds"), new HttpHeaders(), HttpStatus.NO_CONTENT);
}
final Transaction transaction = transactionService.createTransaction(transactionDto);
return new ResponseEntity<>(transaction, new HttpHeaders(), HttpStatus.CREATED);
} catch (Exception ex) {
log.error(MessageConstant.INTERNAL_SERVER_ERROR_MSG + ex.getMessage());
return new ResponseEntity<>(ApiResponseMessage.getInternalServerError(), new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
如果“金额”是,比如说,“sfdfd”,这不是大小数,我们应该提供422。但如果“金额”为“-12.3343”,则这是约束验证错误,但数据有效且可分析。所以我们不能拥有422。
这是我的异常处理课,
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@Override
@Nonnull
protected ResponseEntity<Object> handleMissingServletRequestParameter(
MissingServletRequestParameterException ex,
@Nonnull HttpHeaders headers,
@Nonnull HttpStatus status,
@Nonnull WebRequest request
) {
String error = ex.getParameterName() + " parameter is missing";
return new ResponseEntity<>(ApiResponseMessage.getGenericApiResponse(Boolean.FALSE, HttpStatus.BAD_REQUEST,
error), new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
@Override
@Nonnull
protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(
@Nonnull HttpMediaTypeNotSupportedException ex,
@Nonnull HttpHeaders headers,
@Nonnull HttpStatus status,
@Nonnull WebRequest request
) {
String message = prepareMessageFromException(ex, (ServletWebRequest) request);
return new ResponseEntity<>(ApiResponseMessage.getGenericApiResponse(Boolean.FALSE, HttpStatus.UNSUPPORTED_MEDIA_TYPE,
" media type is not supported. Supported media types "), new HttpHeaders(), HttpStatus.UNSUPPORTED_MEDIA_TYPE);
}
@Override
@NonNull
protected ResponseEntity<Object> handleMethodArgumentNotValid(
@NonNull MethodArgumentNotValidException ex,
@NonNull HttpHeaders headers,
@NonNull HttpStatus status,
@NonNull WebRequest request
) {
String message = prepareMessageFromException(ex, (ServletWebRequest) request);
ApiErrorResponse apiError = new ApiErrorResponse(BAD_REQUEST);
apiError.setMessage("Validation error");
apiError.addValidationErrors(ex.getBindingResult().getFieldErrors());
apiError.addValidationError(ex.getBindingResult().getGlobalErrors());
return buildResponseEntity(apiError);
}
@ExceptionHandler(ConstraintViolationException.class)
protected ResponseEntity<Object> handleConstraintViolation(ConstraintViolationException ex) {
ApiErrorResponse apiError = new ApiErrorResponse(BAD_REQUEST);
apiError.setMessage("Validation error");
apiError.addValidationErrors(ex.getConstraintViolations());
return buildResponseEntity(apiError);
}
@ExceptionHandler(Exception.class)
@ResponseBody
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
ServletWebRequest req = (ServletWebRequest) request;
String message = prepareMessageFromException(ex, (ServletWebRequest) request);
log.info("{} to {}", req.getHttpMethod(), req.getRequest().getServletPath());
log.error(message, ex);
return new ResponseEntity<>(ApiResponseMessage.getGenericApiResponse(Boolean.FALSE, HttpStatus.BAD_REQUEST,
message), new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
@Override
@Nonnull
protected ResponseEntity<Object> handleHttpMessageNotReadable(
@Nonnull HttpMessageNotReadableException ex,
@Nonnull HttpHeaders headers,
@Nonnull HttpStatus status,
@Nonnull WebRequest request
) {
String message = prepareMessageFromException(ex, (ServletWebRequest) request);
return new ResponseEntity<>(ApiResponseMessage.getGenericApiResponse(Boolean.FALSE, BAD_REQUEST,
message), new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
private String prepareMessageFromException(Exception ex, ServletWebRequest request) {
String message = ex.getMessage();
log.info("{} to {}", request.getHttpMethod(), request.getRequest().getServletPath());
log.error(message);
if (message != null && !message.isEmpty()) {
message = message.split(":")[0];
}
return message;
}
@Override
@Nonnull
protected ResponseEntity<Object> handleHttpMessageNotWritable(
@Nonnull HttpMessageNotWritableException ex,
@Nonnull HttpHeaders headers,
@Nonnull HttpStatus status,
@Nonnull WebRequest request
) {
String error = "Error writing JSON output";
return new ResponseEntity<>(ApiResponseMessage.getGenericApiResponse(Boolean.FALSE, HttpStatus.INTERNAL_SERVER_ERROR,
"Internal server error. please contact support !!"), new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
}
@Override
@Nonnull
protected ResponseEntity<Object> handleNoHandlerFoundException(
NoHandlerFoundException ex,
@Nonnull HttpHeaders headers,
@Nonnull HttpStatus status,
@Nonnull WebRequest request
) {
return new ResponseEntity<>(ApiResponseMessage.getGenericApiResponse(Boolean.FALSE, HttpStatus.BAD_REQUEST,
String.format("Could not find the %s method for URL %s", ex.getHttpMethod(), ex.getRequestURL())), new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
private ResponseEntity<Object> buildResponseEntity(ApiErrorResponse apiError) {
return new ResponseEntity<>(apiError, apiError.getStatus());
}
@ExceptionHandler(EntityNotFoundException.class)
protected ResponseEntity<Object> handleEntityNotFound(EntityNotFoundException ex) {
return new ResponseEntity<>(ApiResponseMessage.getGenericApiResponse(Boolean.FALSE, HttpStatus.NOT_FOUND,
"Resource not found: "), new HttpHeaders(), HttpStatus.NOT_FOUND);
}
@ExceptionHandler(DataIntegrityViolationException.class)
protected ResponseEntity<Object> handleDataIntegrityViolation(DataIntegrityViolationException ex, WebRequest request) {
if (ex.getCause() instanceof ConstraintViolationException) {
return new ResponseEntity<>(ApiResponseMessage.getGenericApiResponse(Boolean.FALSE, HttpStatus.CONFLICT,
"Database error"), new HttpHeaders(), HttpStatus.CONFLICT);
}
return new ResponseEntity<>(ApiResponseMessage.getGenericApiResponse(Boolean.FALSE, HttpStatus.INTERNAL_SERVER_ERROR,
"Internal server error. please contact support !!" + ex.getMessage()), new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
protected ResponseEntity<Object> handleMethodArgumentTypeMismatch(MethodArgumentTypeMismatchException ex, WebRequest request) {
return new ResponseEntity<>(ApiResponseMessage.getGenericApiResponse(Boolean.FALSE, HttpStatus.BAD_REQUEST,
String.format("The parameter '%s' of value '%s' could not be converted to type '%s'", ex.getName(), ex.getValue(), ex.getRequiredType())), new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
}
目前,我在提到的两个案例中都得到了400英镑。如何重构代码以获得正确的响应代码?
在对现有代码进行一些修改后,我成功地实现了这一点,
@Override
@Nonnull
protected ResponseEntity<Object> handleHttpMessageNotReadable(
@Nonnull HttpMessageNotReadableException ex,
@Nonnull HttpHeaders headers,
@Nonnull HttpStatus status,
@Nonnull WebRequest request
) {
String message = prepareMessageFromException(ex, (ServletWebRequest) request);
final Throwable throwableCause = ex.getCause();
if (throwableCause instanceof InvalidFormatException) {
return new ResponseEntity<>(ApiResponseMessage.getGenericApiResponse(Boolean.FALSE, HttpStatus.UNPROCESSABLE_ENTITY,
message), new HttpHeaders(), HttpStatus.UNPROCESSABLE_ENTITY);
}
return new ResponseEntity<>(ApiResponseMessage.getGenericApiResponse(Boolean.FALSE, HttpStatus.BAD_REQUEST,
message), new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
因此,当throwable为InvalidFormatException时,我将返回422响应状态代码,其他方法与之前一样工作。
本文向大家介绍Springboot之自定义全局异常处理的实现,包括了Springboot之自定义全局异常处理的实现的使用技巧和注意事项,需要的朋友参考一下 前言: 在实际的应用开发中,很多时候往往因为一些不可控的因素导致程序出现一些错误,这个时候就要及时把异常信息反馈给客户端,便于客户端能够及时地进行处理,而针对代码导致的异常,我们一般有两种处理方式,一种是throws直接抛出,一种是使用try.
我使用的是Nifi 0.4.1版本。我写自定义代码转换CSV到avro格式。我已经创建了类文件,并能够生成nar文件。将nar文件放置在lib目录中,并重新启动nifi服务器。 任何帮助都很感激.. 谢谢,
本文向大家介绍SpringBoot错误处理机制以及自定义异常处理详解,包括了SpringBoot错误处理机制以及自定义异常处理详解的使用技巧和注意事项,需要的朋友参考一下 上篇文章我们讲解了使用Hibernate Validation来校验数据,当校验完数据后,如果发生错误我们需要给客户返回一个错误信息,因此这节我们来讲解一下SpringBoot默认的错误处理机制以及如何自定义异常来处理请求错误。
我正在使用来自外部API的一些RESTendpoint,为此我正在使用REST模板接口。当我从这些调用中收到某些HTTP状态代码时,我希望能够抛出自定义应用程序异常。为了实现它,我正在实现ResponseErrorHandler接口,如下所示: 最后,这是客户端代码(无关代码省略): 我的应用程序上下文: 我怀疑我没有正确理解此自定义错误处理的行为。每个rest模板方法都可能抛出一个RestCli
问题内容: 我们正在使用Spring MVC + Spring Security + Hibernate创建一个RESTful API。该API可以生成JSON和HTML。做好弹簧安全性的错误处理让我头疼: 身份验证可以通过多种方式进行:BasicAuth,通过POST请求中的不同参数以及通过Web登录。对于每种身份验证机制,在Spring Security xml配置的名称空间元素中声明了一个过
我来找你是因为我需要你的帮助。 在我的文件camel-context.xml中,我调用了一个存储过程来获取用户的信息。我需要解决的是: 如果存储过程不返回数据,则发送带有超文本传输协议代码404的UserNot的异常(我已经拥有该类)。 我一直在寻找如何做这件事,但找不到任何可以帮助我的东西。我刚刚开始使用这个框架,所以提前非常感谢您的帮助。 这里我的代码: