2017-10-12 99 views
-2

现在,我在Spring 4.中使用@ControllerAdvice。*。 使用beforeBodyWrite方法。我可以知道在@ControllerAdvice中调用了哪个控制器吗?

在控制器类中创建自定义注释。 在@ControllerAdvice处理时获取控制器的信息。

我想知道来自什么是控制器类的请求。

但是,我不知道解决方案。

任何帮助。?

感谢

+0

你想干什么SH? 'beforeBodyWrite()'在'ResponseBodyAdvice'中。你想知道在那里执行的控制器?如果是这样,为什么? – Kayaman

+0

我需要知道控制器的注释。然后创建自定义注记类,在控制器类的方法级别定义注记类。原因,我需要在messageConverter执行之前通过注释来重置数据。 –

+0

一个非常不好的问题,请先阅读本页,然后编辑您的问题:https://stackoverflow.com/help/how-to-ask – Ibo

回答

0

虽然你的问题没有明确说明是什么目的你正在实现,为什么你需要创建一个自定义注解我会后你一些指导说明如何确定的源您RuntimeExceptionControllerAdvice

考虑下列休息控制器:

@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())); 
    } 
} 

这是端点的输出如何看:

Output of First Controller Output of second Controller

我的建议是,与其这样做,你声明自己的一套异常,然后抓住他们您的控制器建议,与他们被抛出的位置无关:

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() { 
     /**...**/ 
    } 
} 
+0

他的'RuntimeException'的来源? – Kayaman

+0

ControllerAdvice用于捕获未经检查且不需要在方法中声明为“throws”的RuntimeException。尽管我可以编辑答案,但采用这种方式是更好的做法(在我看来)。 –

+0

异常处理是'@ ControllerAdvice'的常见用法,但它不是唯一的。他没有说任何有关例外的事情。事实上,目前还不清楚他在说什么,以及它是否与'@ ControllerAdvice'有关... – Kayaman

相关问题