如何正确抛出和检测此异常

How to throw and detect this exception correct

我正在使用@ControllerAdvice 来检测应用程序中抛出的异常。

试图在创建 class 期间抛出异常:

    public void setStatus(String status) throws InvalidInputStatusException{
       if(checkIfStatusIsAllowed(status)) {
           this.status = status;
       } else {
           throw new InvalidInputStatusException();
       }

    }

正在尝试捕获错误:

@ControllerAdvice
public class RekvisisjonRESTControllerExceptionHandler {

    //TODO: Add logger here!

    @ExceptionHandler
    public final ResponseEntity<RekvisisjonRESTErrorResponse> handleException(InvalidInputStatusException e, WebRequest request) {
        //TODO: Do some logging
        return new ResponseEntity<>(new RekvisisjonRESTErrorResponse(HttpStatus.BAD_REQUEST.toString(),
                e.getClass().getName(),
                e.getMessage(), LocalDateTime.now()), HttpStatus.BAD_REQUEST);
    }
}

我想要的是返回上面指定的对象,但我在这里得到了这个废话:

  "error": "Bad Request",
    "message": "JSON parse error: Ugyldig status som input; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Ugyldig status som input\n at [Source: (PushbackInputStream); line: 2, column: 12] (through reference chain: no.pasientreiser.atom.rekvisisjon.controller.dto.UpdateRekvisisjonStatusRequest[\"status\"])",
    "trace": "org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Ugyldig status som input; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Ugyldig status som input\n at [Source: (PushbackInputStream); line: 2, column: 12] (through reference chain: no.pasientreiser.atom.rekvisisjon.controller.dto.UpdateRekvisisjonStatusRequest[\"status\"])\n\tat org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:245)\n\tat org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:227)\n\tat org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:205)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:158)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:131)\n\tat org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)\n\tat org.springframework.web.me

我假设它未能检测到预期的异常,因为在它之前抛出了另一个异常,但这不是我想要的。

有什么建议吗?

异常不是发生在您的业务代码中,而是发生在将请求解析为您的请求表示对象期间。 Spring Web 将解析请求期间发生的任何类型的异常视为表示级错误,而不是业务级错误,因此,您的异常处理程序不会被调用。

由于您试图在此处强制执行业务规则,我建议将其从表示对象的 setter 方法中移出,并为它找到一个更好的位置。例如。将此逻辑放在业务实体或您的一项服务中,或者至少放在接受请求的控制器方法中。

首先,您的 RekvisisjonRESTControllerExceptionHandler 应该从 ResponseEntityExceptionHandler 扩展。 如果您 return ResponseEntity,它将包装您的值 class (RekvisisjonRESTErrorResponse)。 这里你的异常是在建议之后生成的,当 json 序列化时。

异常处理程序处理处理程序方法中发生的异常(请参阅 https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc)。您看到的异常发生较早,而 Spring 正试图将 JSON 请求正文转换为 UpdateRekvisisjonStatusRequest。 Jackson JSON 反序列化器正在调用 setStatus 方法并遇到异常,Spring 认为 HTTP 正文不可读(因为 Jackson 无法反序列化它)。

看看 Spring MVC 如何处理验证:https://spring.io/guides/gs/validating-form-input/