Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The handling method of java backend Project exception

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

The main content of this article is "how to handle exceptions in java backend projects". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "java back-end project exception handling methods" it!

1. Controller local exception handling 1.1. Use the example

This exception handling is only local to a certain Controller, such as:

@ Controller@Slf4j@RequestMapping ("/ api/demo") public class DemoController {@ ExceptionHandler (Exception.class) @ ResponseBody public ResponseDTO exceptionHandler (Exception e) {log.error ("[{}] system error", e); return ResponseDTO.builder () .errorCode (ErrorCode.SYSTEM_ERROR) .build ();}}

All exceptions thrown by Controller methods (that is, methods annotated by RequestMapping) are handled by this exception handling method.

In use, within Controller, the method annotated with @ ExceptionHandler will be used as the exception handling method within the Controller.

Moreover, it can be injected into its parameters, such as WebRequest, NativeWebRequest, etc., to get the data related to the request.

It can return String to represent a view name, or it can return an object and decorate it with @ ResponseBody, which will be serialized by other mechanisms of the framework.

In addition, it has fine-grained control over the exception type, and annotations allow you to selectively specify the exception type to which the exception handling method applies:

@ ExceptionHandler ({BusinessException.class, DataBaseError.class})

Although global exception handling HandlerExceptionResolver can also be done through conditional judgment, the use of this annotation method is obviously more readable.

II. Examples of using ControllerAdvice2.1

What I just introduced is the local exception handling of Controller, which is very useful for handling unique exception handling within the Controller.

First, define a class that holds the exception handler and decorate it with @ ControllerAdvice.

@ ControllerAdvice (assignableTypes = {GlobalExceptionHandlerMixin.class}) public class ExceptionAdvice {@ ExceptionHandler (ErrorCodeWrapperException.class) @ ResponseBody public ResponseDTO exceptionHandler (ErrorCodeWrapperException e) {if ((errCodeException.getErrorCode (). Equals (ErrorCode.SYSTEM_ERROR) {log.error (e);} return ResponseDTO.ofErroCodeWrapperException (errCodeException);}}

The method modified by @ ExceptionHanlder is written in the same way as the exception handler in Controller.

2.2 Control the range of Controller in effect

Notice that I wrote the annotations like this:

@ ControllerAdvice (assignableTypes = {GlobalExceptionHandlerMixin.class})

It is used to limit the scope of the Controller on which these exception handlers work. If you do not write, the default is valid for all Controller.

This is also the advantage of unified exception handling by ControllerAdvice, which can fine-grained control which Controller the exception handler is valid for. This advantage is:

There can be different exception handlers in a system, and Controller can also choose which one to use more flexibly.

Different business modules may handle exceptions in different ways, which can be done through this mechanism.

Imagine a system that does not use global exception handling at the beginning, if it directly introduces the global exception handling that takes effect in the global scope, it is bound to change the behavior of the existing Controller and be intrusive. That is, if you do not control the effective scope, it takes effect by default for all Controller. If you control the effective scope, it does not take effect by default for all Controller, reducing intrusiveness.

As in the example just now, it is only valid for classes that implement GlobalExceptionHandlerMixin interface:

@ Controller@Slf4j@RequestMapping ("/ api/demo") public class DemoController implements GlobalExceptionHandlerMixin {}

Limited scope of ControllerAdvice support:

Press the note: @ ControllerAdvice (annotations = RestController.class)

Press package name: @ ControllerAdvice ("org.example.controllers")

By type: @ ControllerAdvice (assignableTypes = {ControllerInterface.class, AbstractController.class})

III. Summary

The above methods are mechanisms specially designed by Spring for exception handling.

Personally, because ControllerAdvice has finer-grained control, I prefer to use ControllerAdvice for unified exception handling in the system.

In addition to using exceptions to pass unexpected errors in the system, it is also used to pass business errors that are part of the interface behavior.

This is also one of the advantages of exceptions. If the implementation of the interface is complicated, it is implemented in multiple layers of functions, and if the error code is passed directly, then each layer of function on the path to Controller needs to check the error code, returning to the terrible "write one-line statement to check the error code" mode in C language.

Of course, in theory, any mechanism that can add facets to Controller can handle unified exception handling in disguise. For example:

Catch Controller exceptions in the interceptor and do unified exception handling.

Use Spring's AOP mechanism to do unified exception handling.

At this point, I believe you have a deeper understanding of the "java back-end project exception handling methods", might as well come to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report