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

What's the difference between @ RestControllerAdvice and @ ControllerAdvice?

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article will explain in detail what is the difference between @ RestControllerAdvice and @ ControllerAdvice. The content of the article is of high quality, so the editor will share it with you for reference. I hope you will have some understanding of the relevant knowledge after reading this article.

The difference between @ RestControllerAdvice and @ ControllerAdvice

The @ RestControllerAdvice annotation and the @ ControllerAdvice annotation are located under the same dependency package, and their pom dependencies are:

Org.springframework spring-web 5.3.3

Sometimes you will find that in different projects, in the global exception handling section, some custom classes add @ RestControllerAdvice annotations, and some custom classes add @ ControllerAdvice annotations.

In fact, the role of the two annotations is basically the same, both are to achieve custom global exception handling

The only difference is that @ RestControllerAdvice annotations contain @ ControllerAdvice annotations and @ ResponseBody annotations.

The source code of @ ControllerAdvice annotation is @ Target ({ElementType.TYPE}) @ Retention (RetentionPolicy.RUNTIME) @ Documented@Componentpublic @ interface ControllerAdvice {} @ RestControllerAdvice. The source code of @ Target ({ElementType.TYPE}) @ Retention (RetentionPolicy.RUNTIME) @ Documented@ControllerAdvice@ResponseBodypublic @ interface RestControllerAdvice {}

When the custom class is annotated with @ ControllerAdvice, and the method needs to return json data, each method also needs to add the @ ResponseBody annotation

When a custom class is annotated with @ RestControllerAdvice, the method automatically returns json data. There is no need to add @ ResponseBody annotation to each method.

/ * Global exception handling class * / @ RestControllerAdvice@Slf4jpublic class GlobalExceptionHandler {@ ExceptionHandler (Exception.class) public Result ExceptionHandler (Exception e) {log.error ("exception occurs:", e); return Result.failed (e.getMessage ());} @ RestControllerAdvice@ ControllerAdvice annotation invalid generic exception handling

For a simple record, we plan to write a common exception handling aspect today, which is mainly to intercept all thrown exceptions and return them to the front end, which is the error code, the cause of the error and so on. Prevent errors from being thrown directly at the front end.

@ RestControllerAdvice or @ ControllerAdvice can be treated directly as aspects of error handling. However, I found that these two annotations were invalid during use because I defined GlobalExceptionHandler in another package, and @ SpringBootApplication could not be automatically loaded into that annotation. (the default scan path for the springboot startup class is all java classes under the package in which the class resides.

For example, if the startup class is under the "com.galen.cloud.portal" package, only the classes under the com.galen.cloud.portal package will be scanned and loaded. So just add the corresponding scanBasePackages (scan all the packages that match the com.galen.* here instead):

Launch class package com.galen.cloud.portal;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication (scanBasePackages = "com.galen.*") public class galenPortalApplication {public static void main (String [] args) {SpringApplication.run (galenPortalApplication.class, args);}} error handling class package com.galen.common.exception;import com.galen.common.core.domain.R;import org.slf4j.Logger;import org.slf4j.LoggerFactory Import org.springframework.core.annotation.AnnotationUtils;import org.springframework.dao.DuplicateKeyException;import org.springframework.http.HttpStatus;import org.springframework.web.HttpRequestMethodNotSupportedException;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseStatus;import org.springframework.web.bind.annotation.RestControllerAdvice;/** * exception handler * @ author galen * / @ RestControllerAdvicepublic class GlobalExceptionHandler {private Logger logger = LoggerFactory.getLogger (getClass ()) / * * request method does not support * / @ ExceptionHandler ({HttpRequestMethodNotSupportedException.class}) @ ResponseStatus (code = HttpStatus.METHOD_NOT_ALLOWED) public R handleException (HttpRequestMethodNotSupportedException e) {logger.error (e.getMessage (), e); return R.error ("does not support'" + e.getMethod () + "request") } / * intercepts unknown runtime exceptions * / @ ExceptionHandler (RuntimeException.class) public R notFount (RuntimeException e) {if (AnnotationUtils.findAnnotation (e.getClass (), ResponseStatus.class)! = null) {throw e;} logger.error ("Runtime exceptions:", e) Return R.error ("Runtime exception:" + e.getMessage ());} / * * handle custom exceptions * / @ ExceptionHandler (galenException.class) public R handleWindException (galenException e) {return R.error (e.getCode (), e.getMessage ()) } @ ExceptionHandler (DuplicateKeyException.class) public R handleDuplicateKeyException (DuplicateKeyException e) {logger.error (e.getMessage (), e); return R.error ("the record already exists in the database");} @ ExceptionHandler (Exception.class) public R handleException (Exception e) throws Exception {logger.error (e.getMessage (), e); return R.error ("server error, please contact the administrator") } / * captures and handles unauthorized exceptions * * @ param e authorization exceptions * @ return uniformly encapsulated result class, containing code code and prompt message msg * / @ ExceptionHandler (UnauthorizedException.class) public R handle401 (UnauthorizedException e) {return R.error (401, e.getMessage ()) } / / Verification code error @ ExceptionHandler (ValidateCodeException.class) public R handleCaptcha (ValidateCodeException e) {return R.error (e.getMessage ());}}

The final interception effect is as follows:

So much for sharing the difference between @ RestControllerAdvice and @ ControllerAdvice. I hope the above content can be helpful to you and learn more. If you think the article is good, you can share it for more people to see.

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

Development

Wechat

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

12
Report