方法注释可以处理此方法引发的错误吗? [英] Can a method annotation handle errors thrown by this method?
问题描述
我最近开始学习注释,我想知道方法注释可以处理此方法引发的错误吗?或了解此异常/错误的代码.
I recently started learning annotations and I want to know can a method annotation handle errors thrown by this method? Or to know the code of this exception/error.
P.S.如果可以的话,下一步是根据错误代码重试此方法
P.S. if it can, next step is to retry this method in dependence of error code
P.S.S.我知道spring Retryable,但是我不能使用它.我试图在Google中找到有关我的问题的信息,但没有找到.
P.S.S. I know about spring Retryable, but i can't use it. I tried to find info about my question in the google, but i didn't find.
推荐答案
实际上,OOP中的基本要素之一是IoC(控制反转).在构建专业应用程序时,我们需要注意这种方法.
Actually,One of the basic things in OOP is IoC(Inversion of Control).We need to care this approach when building a professional application.
https://www.baeldung.com/inversion弹簧中的控制和依赖性注射
例如, 我们可以在项目的每个类中编写try/catch块.这是一种不好的做法. 代替这种方式,我们可以使用@ControllerAdvice批注. 只需定义一个特定的异常,JVM就会为您处理所有类/请求中的异常.这就是IoC.
For example, we can write try/catch blocks in each class in the project.this is bad practice. instead of this way ,we can use @ControllerAdvice annotation. Just define a particular exception,JVM catch it in all the classes/requests for you.This is IoC.
如果在放置在@ControllerAdvice批注上的Class中定义异常,则可以在项目中的每个请求中捕获异常.
You can catch exceptions in every request in project,If you define the exception in the Class which you put on the @ControllerAdvice annotation.
简单用法示例:
@ControllerAdvice
@RestController
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public final ResponseEntity httpRequestMethodNotSupportedException(Exception ex, WebRequest request) {
ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), "there isn’t an URL like that",
request.getDescription(false));
return new ResponseEntity<>(exceptionResponse, HttpStatus.METHOD_NOT_ALLOWED);
}
以下是有关@ControllerAdvice的有用链接:
Here is the useful link about @ControllerAdvice:
https://medium.com/@jovannypcg/understanding-springs-controlleradvice -cd96a364033f
这篇关于方法注释可以处理此方法引发的错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!