【问题标题】:Custom exception with spring not thrown没有抛出弹簧的自定义异常
【发布时间】:2018-07-20 04:33:44
【问题描述】:

我用 Spring 5 响应式编写了一个自定义异常

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class AddressNotFoundException extends RuntimeException{
    public AddressNotFoundException(String message) {
        super(message);
    }

我在服务中称它为:

@Override
public Mono<Address> getById(String id) {
    Address addressFound=repository.findById(id).block();
    if(Objects.equals(addressFound, null))
        throw new AddressNotFoundException("Address #"+id+" not found");
    return Mono.just

(addressFound);
    }

但是当我到达此页面时,会引发异常,但不是 404,而是空指针异常和错误 500 页面,但消息正确?

永远不会抛出 AddressNotFound,只有 Nullpointer 异常但带有我的自定义消息??? 你能帮帮我吗?

这是我的控制器:

  @GetMapping("/address/{id}")
    public Mono<Address> byId(@PathVariable String id) {
        return addressService.getById(id);
    }

谢谢

【问题讨论】:

    标签: java spring exception-handling nullpointerexception


    【解决方案1】:

    我尝试过使用 spring boot 1.5 它可以在没有 webflux 的情况下使用 Spring Boot 2 它可以工作,所以 Webflux 似乎无法处理自定义异常???

    【讨论】:

      【解决方案2】:

      您可能有一个 HandlerExceptionResolver bean,由于某种原因导致 500。请尝试将其取下一段时间。

      【讨论】:

        【解决方案3】:

        不要扩展RuntimeException,而是尝试扩展通用Exception

        Spring 提供了一个ControllerAdvice 注释来拦截抛出的异常

        @ControllerAdvice
        public class ExceptionController extends ResponseEntityExceptionHandler {
          @ExceptionHandler(value = { AddressNotFoundException.class })
          protected ResponseEntity<Object> handleAddressNotFoundException(Exception ex, WebRequest request) {
            AddressNotFoundException notFound = (AddressNotFoundException)ex;
            return handleExceptionInternal(ex, String.valueOf(notFound), new HttpHeaders(), HttpStatus.NOT_FOUND, request);
          }
        

        }

        这会将错误以 404 的形式发送回客户端,您可以在客户端消化其中通常以 json 字符串的形式显示给用户。可以覆盖异常 toString 方法以将其作为 json 返回或编写一个辅助方法来执行此操作。

        【讨论】:

        • 仍然无法正常工作 :( 出现意外错误 (type=None, status=999)。
        • 尝试在ExceptionController 中添加另一个方法来捕获NullPointerException 我认为Sudarshana Gurusinghe 提到的事情发生在block() 调用抛出空指针的地方,因为没有对象。尝试摆脱 block() 调用,然后测试 null。
        • 我在另一条路线上尝试了一个简单的 throw new AddressNotFoundException() 并且我遇到了同样的问题
        • 我唯一可以建议的另一件事是将@GetMapping更改为@RequestMapping,然后将'@ResponseBody也添加到方法中,这样它将是public @ResponseBody Mono&lt;Address&gt; byId(@PathVariable String id)
        • 我已经尝试过,但即使是在一个干净的项目 factory.BeanCreationException:创建类路径资源中定义的名称为“requestMappingHandlerMapping”的 bean 时出错
        【解决方案4】:

        如果您的地址为空,

        repository.findById(id).block();

        我想应该抛出 NullPointerException。这样一来,它就永远无法到达代码行来抛出自定义异常。

        【讨论】:

        • 我想,但即使使用简单的路由 public void error() throws AddressNotFoundException { throw ne it doesn't work ?
        猜你喜欢
        • 2017-02-28
        • 1970-01-01
        • 2011-10-06
        • 2011-05-30
        • 2015-07-11
        • 1970-01-01
        • 1970-01-01
        • 2012-09-11
        相关资源
        最近更新 更多