如何使用@ControllerAdvice从Service类捕获异常?



我有一些包含多个抛出错误方法的Service类,下面是一个抛出错误方法的例子:

public Optional<Item> getItemById(Long itemId) throws Exception {
return Optional.of(itemRepository.findById(itemId).
orElseThrow(() -> new Exception("Item with that id doesn't exist")));
}

我应该在@ControllerAdvice注释类中捕获错误吗?我该怎么做呢?

标记为@ControllerAdvice的控制器将拦截在请求到达时调用的堆栈中抛出的任何异常。如果问题是您是否应该用ControllerAdvice捕获错误,则取决于您,但它允许您在抛出异常时自定义行为。为此,您应该创建一个这样的类:

@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler({ Exception.class, MyCustomException.class }) //Which exceptions should this method intercept
public final ResponseEntity<ApiError> handleException(Exception ex){
return new ResponseEntity<>(body, HttpStatus.NOT_FOUND); //Or any HTTP error you want to return
}
}

最新更新