gpt4 book ai didi

java - Spring MVC : determine which controller threw exception in @ExceptionHandler

转载 作者:行者123 更新时间:2023-11-30 07:53:41 24 4
gpt4 key购买 nike

我将 Spring MVC 与 Spring Boot 和 Thymeleaf 结合使用。我有返回 Thymeleaf 模板名称的普通 Controller 和用 @RepsonseBody 注释的 REST Controller 。

假设我有一个 EntityNotFoundException,它是由 Controller 调用的某些代码抛出的。如果抛出,我想分别为 REST Controller 返回 404 状态代码和错误页面或错误消息。

我当前的普通 Controller 设置:

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

@Controller
public class FooController {

@RequestMapping("/foo") public String foo() {
try {
...
} catch (EntityNotFoundException enfe) {
throw new ResourceNotFoundException(enfe.getMessage());
}
return "foo";
}
}

对于 REST Controller ,我不捕获异常并让全局异常处理程序接收它:

@Controller
public class BarController {

@RequestMapping("/bar")
@ResponseBody
public SomeDto bar() throws EntityNotFoundException {
...
return someDto;
}
}

@ControllerAdvice
public class ExceptionHandlerAdvice {

@ExceptionHandler(EntityNotFoundException.class)
public final ResponseEntity<Object> handleEntityNotFoundExceptionEntityNotFoundException enfe) {
return new ResponseEntity<>(enfe.getMessage, HttpStatus.NOT_FOUND);
}
}

我也不想在我的普通 Controller 中捕捉并重新抛出。全局处理程序应该同时处理:

  @ExceptionHandler(EntityNotFoundException.class)
public final Object handleEntityNotFoundException(EntityNotFoundException enfe) {
if (/* is REST controller? */) {
return new ResponseEntity<>(enfe.getMessage(), HttpStatus.NOT_FOUND);
} else {
Map<String, Object> model = ImmutableMap.of("message", enfe.getMessage());
return new ModelAndView("error", model, HttpStatus.NOT_FOUND);
}
}

有没有办法确定异常的来源,即 Controller 是否使用 @ResponseBody 或类似的注释?

最佳答案

我找到了一个解决方案。您可以将当前 Controller 方法作为 HandlerMethod 参数注入(inject)。

  @ExceptionHandler(EntityNotFoundException.class)
public final Object handleEntityNotFoundException(EntityNotFoundException enfe, HandlerMethod handlerMethod) {

boolean isRestController = handlerMethod.hasMethodAnnotation(ResponseBody.class)
|| handlerMethod.getBeanType().isAnnotationPresent(ResponseBody.class)
|| handlerMethod.getBeanType().isAnnotationPresent(RestController.class);

if (isRestController) {
return new ResponseEntity<>(enfe.getMessage(), HttpStatus.NOT_FOUND);
} else {
Map<String, Object> model = ImmutableMap.of("message", enfe.getMessage());
return new ModelAndView("error", model, HttpStatus.NOT_FOUND);
}
}

关于java - Spring MVC : determine which controller threw exception in @ExceptionHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44603942/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com