preface

Recently I had a bit of time off and picked up cicada, an open source project that hadn’t been updated for six months.

Some new friends do not know what this project is? First take a look at the official introduction (in fact, I wrote 😀)

Cicada: fast, lightweight WEB framework based on Netty4 implementation; There are no excessive dependencies, and the core JAR package is only 30KB.

This wheel has been written about before, if you are interested, you can read it again:

  • “Build a Wheel” — CICada (Lightweight WEB Framework)
  • “Make a Wheel” — CICada source code analysis
  • “Build a wheel” — CICada designs a configuration module
  • “Build a Wheel” — CICADA Design Global Context
  • Design an interceptor using the chain of responsibility pattern
  • Design a pluggable IOC container

I’m sure you’ll have a lot more ideas about this little gadget.

The effect

That’s it, back to business; The most commonly used MVC framework is SpringMVC, and trusting global exception handling is essential when scaffolding is built.

Spring usage

Usually we do as follows:

Traditional Spring version:

  • To implement aSpringOwn interface, override the method, the final exception handling is here.
  • Configure this class in theSpringxmlTo register as a beanSpringIn the container.
public class CustomExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
	// Custom processing
}
Copy the code
<bean class="ssm.exception.CustomExceptionResolver"></bean> 
Copy the code

Of course, the popular SpringBoot also has a simplified version:

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public Object defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        // Custom processing}}Copy the code

It’s all annotated, but it’s essentially the same.

Both are to create a special bean in the container, this bean is specifically used to handle exceptions, when the system runs an exception, find the bean from the container, and execute the method.

How this particular bean is identified is either by implementing a specific interface or declaring it with annotations, which corresponds to traditional Spring and SpringBoot usage.

Cicada usage

Cicada also looked at Spring’s design when designing its global exception handler, so its final usage is as follows:

@CicadaBean
public class ExceptionHandle implements GlobalHandelException {
    private final static Logger LOGGER = LoggerBuilder.getLogger(ExceptionHandle.class);

    @Override
    public void resolveException(CicadaContext context, Exception e) {
        LOGGER.error("Exception", e);
        WorkRes workRes = new WorkRes();
        workRes.setCode("500");
        workRes.setMessage(e.getClass().getName() + "Abnormal system operation"); context.json(workRes); }}Copy the code

Define a class that implements the GlobalHandelException interface. When a request fails, the page and background will output the following:

design

The usage is very similar to Spring in that you need to implement an interface GlobalHandelException and use the @cicadabean annotation class to load it into cicada’s built-in IOC container.

When an exception occurs, find the object in the IOC container and call its resolveException.

You can also respond to different outputs (JSON /text/ HTML) via the CicadaContext global context.

Core principles

Briefly draw the flow chart, the steps are as follows:

  • We’ll find the implementation when we initialize itGlobalHandelExceptionInterface class, instantiated and registered toIOCIn the container.
  • Get the exception handler object from the container when an exception occurs and execute its handler function.

Said the principle of a long time to see how to achieve the source code.

When the bean is initialized, if it is an exception handler, it is stored separately (equivalent to marking the bean as described above).

The GlobalHandelException itself is pretty simple:


Next comes the runtime:

When an exception occurs, it will handle the exception through the previously saved exception processing bean, and pass the global context and exception information in the call.

This allows us to implement our own exception-handling logic in this implementation class.

conclusion

In case an interviewer asks you later how SpringMVC exception handling is implemented? You should know how to answer 😏.

At the same time, can you configure an exception handling for a certain controller? In this way, the exceptions generated by each controller can be handled separately. If no exception is configured, the global exception will be entered. The principle is similar, interested friends can propose a PR to complete the feature.

Project source code:

Github.com/TogetherOS/…

Your likes and shares are the biggest support for me