[英]Is there a way to handle an exception thrown from inside of custom exception handler in Spring?
[英]Custom exception with spring not thrown
我在Spring 5 React中编写了一个自定义异常
@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);
}
谢谢
如果您的地址为空,
repository.findById(id).block();
我应该抛出NullPointerException。 这样,它将永远无法到达代码行以引发自定义异常。
除了扩展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返回,也可以编写一个辅助方法来实现。
您可能有一个HandlerExceptionResolver bean,由于某种原因它导致500。 请尝试将其关闭一段时间。
我已经尝试过使用Spring Boot 1.5,它可以在没有webflux的情况下与Spring Boot 2一起使用,所以它似乎无法处理自定义异常?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.