Java 我能知道@ControllerAdvice中调用了哪个控制器吗?
现在,我在Spring 4中使用@ControllerAdvice。*。 使用beforeBodyWrite方法 在控制器类中创建自定义注释。 @ControllerAdvice处理时获取控制器信息 我想知道这个请求来自什么是控制器类 但是,我不知道解决办法 需要帮忙吗Java 我能知道@ControllerAdvice中调用了哪个控制器吗?,java,annotations,Java,Annotations,现在,我在Spring 4中使用@ControllerAdvice。*。 使用beforeBodyWrite方法 在控制器类中创建自定义注释。 @ControllerAdvice处理时获取控制器信息 我想知道这个请求来自什么是控制器类 但是,我不知道解决办法 需要帮忙吗 谢谢尽管您的问题没有明确说明您要实现的目标以及为什么需要创建自定义注释,但我将在ControllerAdvice 给定以下Rest控制器: @RestController public class CARestControlle
谢谢尽管您的问题没有明确说明您要实现的目标以及为什么需要创建自定义注释,但我将在
ControllerAdvice
给定以下Rest控制器:
@RestController
public class CARestController {
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String testException() {
throw new RuntimeException("This is the first exception");
}
}
@RestController
public class CAOtherRestController {
@RequestMapping(value = "/test-other", method = RequestMethod.GET)
public String testOtherException() {
throw new RuntimeException("This is the second exception");
}
}
如果两者都抛出异常,我们可以使用以下ControllerAdvice
捕获该异常,并使用堆栈跟踪确定异常的来源
@ControllerAdvice
public class CAControllerAdvice {
@ExceptionHandler(value = RuntimeException.class)
protected ResponseEntity<String> handleRestOfExceptions(RuntimeException ex) {
return ResponseEntity.badRequest().body(String.format("%s: %s", ex.getStackTrace()[0].getClassName(), ex.getMessage()));
}
}
@ControllerAdvice
公共类CAControllerAdvice{
@ExceptionHandler(值=RuntimeException.class)
受保护的响应HandlerEstofeExceptions(RuntimeException ex){
返回ResponseEntity.badRequest().body(字符串.格式(“%s:%s”,例如getStackTrace()[0].getClassName(),例如getMessage());
}
}
以下是端点输出的外观:
我的建议是,不要这样做,而是声明自己的异常集,然后在控制器建议中捕获它们,独立于抛出它们的位置:
public class MyExceptions extends RuntimeException {
}
public class WrongFieldException extends MyException {
}
public class NotFoundException extends MyException {
}
@ControllerAdvice
public class CAControllerAdvice {
@ExceptionHandler(value = NotFoundException .class)
public ResponseEntity<String> handleNotFound() {
/**...**/
}
@ExceptionHandler(value = WrongFieldException .class)
public ResponseEntity<String> handleWrongField() {
/**...**/
}
}
公共类MyExceptions扩展RuntimeException{
}
公共类ErrorFieldException扩展了MyException{
}
公共类NotFoundException扩展了MyException{
}
@控制器建议
公共类CAControllerAdvice{
@ExceptionHandler(值=NotFoundException.class)
公共响应handleNotFound(){
/**...**/
}
@ExceptionHandler(值=ErrorFieldException.class)
公共责任handleWrongField(){
/**...**/
}
}
他的RuntimeException
?ControllerAdvice用于捕获未经检查的运行时异常,不需要在方法中声明为抛出。在我看来,这样做是一种更好的做法,尽管我可以编辑答案。异常处理是@ControllerAdvice
的常用方法,但它不是唯一的一种。他没有说任何关于例外的事情。事实上,不清楚他在说什么,也不清楚这是否与@ControllerAdvice
有关……你是对的,我的错,我误解了这个问题。它真的需要一些编辑。谢谢!对我很有帮助。我有个主意!你想完成什么beforeBodyWrite()
位于ResponseBodyAdvice
中。你想知道在那里执行的控制器吗?如果是,为什么?我需要知道控制器的注释。创建自定义注释类,然后在控制器类的方法级别上定义注释类。因为,我需要在messageConverter执行之前通过注释重置数据。一个问题问得很糟糕,请先阅读此页,然后编辑您的问题: