Reputation: 2226
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. 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.
Upvotes: 0
Views: 2514
Reputation: 264
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
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.
You can catch exceptions in every request in project,If you define the exception in the Class which you put on the @ControllerAdvice annotation.
Simple Usage Example :
@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);
}
Here is the useful link about @ControllerAdvice:
https://medium.com/@jovannypcg/understanding-springs-controlleradvice-cd96a364033f
Upvotes: 1
Reputation: 140427
You are probably more thinking about Aspect Oriented Programming.
Meaning: java annotations aren't about adding functionality "into" methods. They are markers that are "evaluated" by some sort of component (either the compiler at compile time, or some framework at run time) and trigger activity in that component.
In order to really manipulate the behavior a method (like: add automated tracing/logging code), you need something like AOP. Of course: the whole purpose of compiler-annotations are about generating code based upon the annotation. Project Lombok is a good example for such things: you put annotations into your source code, and the compiled class file contains many things inserted by Lombok during compile.
Upvotes: 2
Reputation: 955
Annotation on its own does nothing. It is just to mark code. You need to have some handlers, that scan your classes and react in case of annotation.
Most frameworks already have handlers and scanners, so developer include proper framework, add proper annotations, and thanks to that frameworks will perform some work for developer or application.
btw, for error handling, I recommend using a simple proxy like this: Invoke method in another class's try catch block
Upvotes: 2