我有一个 @ControllerAdvice 扩展 ResponseEntityExceptionHandler 作为我尝试控制 API 调用工作流程中引发的任何异常的标准响应。
没有控制器的建议。我得到了 spring 生成的基于 HTML 的通用响应,带有正确的响应头。但是当我添加 @ControllerAdvice 时,Spring 不会响应通用错误正文。正文为空,具有正确的响应标头
@Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
String erroMessage = "Required Parameter: '"+ex.getParameterName()+"' was not available in the request.";
TrsApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, erroMessage, ex, ApiErrorCode.INVALID_REQUEST);
return buildResponseEntity(apiError);
}
Run Code Online (Sandbox Code Playgroud)
因此,现在如果请求中缺少必需的参数,流程会很好地触发我的覆盖实现,并使用描述错误的 JSON 有效负载进行响应。但是,如果出现任何其他异常,如 HttpMediaTypeNotAcceptableException,spring 会以空体响应。
在我添加我的建议之前,spring 正在响应通用错误响应。我是 Spring Boot 生态系统的新手。需要帮助了解这是否是预期行为,是否有更好的方法来实现集中错误处理。
为了在整个应用程序中实现统一的异常处理,我将REST错误处理与Spring solution#3 @ControllerAdvice一起使用,并与一起使用@ExceptionHandler。
春季版本:4.3.22.RELEASE
Spring Boot版本:1.5.19.RELEASE
这是一个Spring Boot应用程序,下面是我的程序包结构。
src/main/java
com.test.app.controller
MyRestController.java -- This is my Rest controller
com.test.app.handler
RestExceptionHandler.java -- This is my ControllerAdvice class
Run Code Online (Sandbox Code Playgroud)
以下是我的ControllerAdvice代码,其中一个Controller引发,InvalidDataException但仍未@ExceptionHandler调用相应的控制器。相反,我Unexpected 'e'使用http 400作为响应正文。
@ControllerAdvice
public class RestExceptionHandler {
@ExceptionHandler(InvalidDataException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public @ResponseBody ErrorResponse handleValidationError(final InvalidDataException ex,
final WebRequest request) {
log.error("InvalidDataException message:{} ", ex.getMessage());
return getExceptionResponse("Failed with Invalid data" + ex.getMessage(), HttpStatus.BAD_REQUEST.value());
}
private ErrorResponse getExceptionResponse(final String message, final Integer errorCode) …Run Code Online (Sandbox Code Playgroud) exceptionhandler spring-boot spring-restcontroller controller-advice
如何让 controllerAdvice 类捕获从 completablefutrue 抛出的异常。在下面的代码中,我有一个checkId抛出已检查异常的方法。我使用 completablefuture 调用此方法并将已检查的异常包装在 CompletionException 中。虽然我在控制器通知类中有一个处理程序方法,但它没有处理错误。
package com.example.demo.controller;
@RestController
public class HomeController {
@GetMapping(path = "/check")
public CompletableFuture<String> check(@RequestParam("id") int id) {
return CompletableFuture.supplyAsync(() -> {
try {
return checkId(id);
}
catch (Exception e) {
throw new CompletionException(e);
}
});
}
public String checkId(int id) throws Exception {
if (id < 0) {
throw new MyException("Id must be greater than 0");
}
return "id is good";
}
}
Run Code Online (Sandbox Code Playgroud)
——
package com.example.demo;
public class MyException extends …Run Code Online (Sandbox Code Playgroud) 我有一个控制器建议类,但我似乎无法让它返回 XML,即使我使用了注释@RequestMapping。这是一个精简的示例。
@RestControllerAdvice
public class ControllerAdvice {
@ExceptionHandler(Exception.class)
@RequestMapping(produces = MediaType.APPLICATION_XML_VALUE)
public PriceAvailabilityResponse handleControllerErrorXML(final Exception e) {
e.printStackTrace();
System.out.println("Exception Handler functional");
PriceAvailabilityResponse priceAvailabilityResponse = new PriceAvailabilityResponse();
priceAvailabilityResponse.setStatusMessage("Server Error");
priceAvailabilityResponse.setStatusCode(99);
return priceAvailabilityResponse;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意其余控制器如何@RequestMapping(produces = MediaType.APPLICATION_XML_VALUE)工作来控制响应的形成方式。
PriceAvailabilityResponse这是上述代码块中可能包含的内容的示例。
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@Getter
@Setter
public class PriceAvailabilityResponse {
@JacksonXmlProperty(isAttribute = true, localName = "StatusCode")
@JsonProperty(value = "StatusCode", required = false)
private int statusCode = 0;
@JacksonXmlProperty(isAttribute = true, localName = "StatusMessage")
@JsonProperty(value = "StatusMessage", required = false) …Run Code Online (Sandbox Code Playgroud) 我正在开发 Spring Boot 中异常处理的示例演示应用程序。我正在尝试使用 @ControllerAdvice 进行异常处理。
我想处理验证器抛出的异常。它处理其他异常,但不处理 MethodArgumentNotValidException。
有关更多详细信息,以下是我正在研究的课程:
查询.java
@Getter
@Setter
@NoArgsConstructor
@Validated
public class Query implements Serializable{
@Size(min = 7, max = 24, message = "Size must be between 7 and 24")
@Pattern(regexp = "[a-zA-Z0-9 ]+", Invalid characters")
private String number;
@Size(max = 2, message = "Size must be between 0 and 2")
@Pattern(regexp = "[a-zA-Z0-9 ]+", message="Invalid characters")
private String language;
}
Run Code Online (Sandbox Code Playgroud)
错误响应.java
@Setter
@Getter
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
public class ErrorResponse
{
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = …Run Code Online (Sandbox Code Playgroud) java validation error-handling spring-boot controller-advice
Spring 5 引入了 ResponseStatusException,这让我陷入了困境,不知道在什么情况下可以使用 ResponseStatusException 和 ControllerAdvice,因为它们非常相似。
谁能帮我这个?
error-handling exception response httpresponse controller-advice
我有一个带有控制器和服务的 springboot 项目。和 GlobalExceptionHandler 像 -
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(DataIntegrityViolationException.class)
public ResponseEntity<Object> handle(DataIntegrityViolationException e, WebRequest request) {
....
String requestPath = ((ServletWebRequest)request).getRequest().getRequestURI();
// I am using this requestPath in my output from springboot
...
}
}
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我如何在我的单元测试类中编写模拟吗
((ServletWebRequest)request).getRequest().getRequestURI()
我需要添加@ControllerAdvice类来处理异常并返回带有来自异常的消息的正文。
但是,当通过邮递员检查时,即使我的 ControllerAdvice 类方法内的断点触发,我仍然会收到带有 500Internal Server Error 的默认正文。
控制台日志:
WARN 24909 --- [nio-8081-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Failure in @ExceptionHandler com.javalibrary.controller.ControllerAdvice#handleApplicationException(RuntimeException)
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:315) ~[spring-webmvc-5.3.18.jar:5.3.18]
at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:219) ~[spring-webmvc-5.3.18.jar:5.3.18]
Run Code Online (Sandbox Code Playgroud)
响应正文:
WARN 24909 --- [nio-8081-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Failure in @ExceptionHandler com.javalibrary.controller.ControllerAdvice#handleApplicationException(RuntimeException)
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:315) ~[spring-webmvc-5.3.18.jar:5.3.18]
at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:219) ~[spring-webmvc-5.3.18.jar:5.3.18]
Run Code Online (Sandbox Code Playgroud)
我的ControllerAdvice课:
{
"timestamp": "2022-04-18T19:13:14.183+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/api/v1/book/1"
}
Run Code Online (Sandbox Code Playgroud)
build.gradle插件:
plugins {
id 'org.springframework.boot' version '2.6.6'
id …Run Code Online (Sandbox Code Playgroud) spring-boot ×6
java ×5
spring ×3
exception ×1
httpresponse ×1
java-8 ×1
json ×1
response ×1
rest ×1
validation ×1
xml ×1