Answer the question
In order to leave comments, you need to log in
How is exception handling implemented in corporate projects?
Hello!
I am writing a spring project, in the project I use spring framework, spring security, spring mvc, spring data, hibernate, mysql, java 8, rest technologies. Many questions arise during the development process, one of them concerns the handling of exceptions on large enterprise projects. On past projects, I somehow didn’t quite understand how exception handling is implemented. Yes, and on my own, somehow I can’t figure it out, I don’t understand this exception handling and that’s it). Can you please tell me how exception handling is implemented on large projects? If possible with examples. More detailed questions.
1-how to handle database errors (Mysql) konstrany, length, fell off the connection to the database, etc.?
2nd i use rest, in response to client i send wrapper
Response<T>{
private boolean status;
private T data;
private Error error;
} при ошибки в него кладу объект
Error {
private ErrorReason reason; //enum
private List<ErrorEnum> messages;
}
Answer the question
In order to leave comments, you need to log in
In order to handle exceptions, you can:
1. Use the annotation @ExceptionHandler
. In order not to prescribe it in each controller and not use inheritance, it can be applied to a method in a class with an annotation @ControllerAdvice
2. Implement your own HandlerExceptionResolver
and register it inWebMvcConfigurer
In Spring, you can define a handler for all exceptions and errors through the @ExceptionHandler annotation, create a base controller with a method and this annotation, such as BaseRestController , and inherit all controllers from it. Inside the method, return a JSON object with error status 500 and error text, and don't forget to log the exception, if necessary (for example, via slf4j).
500 status indicates that an internal error has occurred, there are no http statuses for database errors.
This will be enough.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question