有没有办法在异常处理程序中访问 POST 请愿书的正文?



在Spring Boot API Rest应用程序中,我有一个给定RestControllerExceptionHandler。此控制器具有@RequestBody注释,该注释是其方法之一中的String

@RestController
public class FooController {
@PostMapping("/my_url")
public ResponseEntity myMethod(@RequestBody String param) { 
....
}
@ExceptionHandler({MyCustomException.class})
public ResponseEntity handleMyCustomException(MyCustomException ex) {
...
}
}

我无法以@ExceptionHandler方法访问上述String(对应于标题所说的POST请愿书的正文(

我可以在WebRequest中设置param变量,然后通过handle方法检索它,但这似乎是一种非常黑客的实现方式。

框架是否提供了在ExceptionHandler中访问POST请愿书正文的解决方案?

我认为你问的问题和这个问题是一样的。 不幸的是,似乎没有一个优雅而简单的解决方案。

由于您正在抛出自定义异常,因此您可以考虑在异常中添加一个属性来保存该额外信息(即参数(。

这是你要找的吗?

@ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {
/**Here you can inject any you spring beans**/
@ExceptionHandler({ MyCustomException.class })
protected ResponseEntity<Object> handleInvalidRequest(RuntimeException exc, WebRequest request) {
MyCustomException exception = (MyCustomException) exc;
/**here you can do watewer you want with an exception and a body**/
HttpHeaders headers = new HttpHeaders();
/**here you have to create some response objects if needed**/
YourExceptionWrapper error = new YourExceptionWrapper(exception.getMessage());
headers.setContentType(MediaType.APPLICATION_JSON);
/**and then send a bad request to a front-end**/
return handleExceptionInternal(exc, error, headers, HttpStatus.BAD_REQUEST, request);
}
}

最新更新