方法注释可以处理此方法抛出的错误吗? [英] Can a method annotation handle errors thrown by this method?

查看:22
本文介绍了方法注释可以处理此方法抛出的错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始学习注解,我想知道一个方法注解可以处理这个方法抛出的错误吗?或者想知道这个异常/错误的代码.

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. if it can, next step is to retry this method in dependence of error code

P.S.S.我知道 spring Retryable,但我不能使用它.我试图在谷歌中找到有关我的问题的信息,但我没有找到.

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-control-and-dependency-injection-in-spring

例如,我们可以在项目的每个类中编写 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 注释上的类中定义异常.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆