本文主要是介绍controller 异常统一处理的四种方式,透过这四种方式看spring注解的派生性,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.当在一个Controller中任何一个方法发生异常,一定会被这个方法拦截到。
由于这里controller是@RestController 注解的,等于每个方法已经添加了@ResponseBody注解,下面是@RestController 的源码
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
@RestController
@RequestMapping("ziyue/GroupPortraitFacade")
public class GroupPortraitController {@PostMapping("upload")public ObjectResult<UploadResultDTO> upload(MultipartFile file){return groupPortraitFacade.upload(Long.valueOf(SsoContextHolder.getSsoUserInfo().getUserCode()),file);}@ExceptionHandler(MaxUploadSizeExceededException.class)public String handleException(MaxUploadSizeExceededException ex) {ObjectResult objectResult = new ObjectResult(false);objectResult.setMessage("文件应不大于 "+ getFileKB(ex.getMaxUploadSize()));return JsonUtil.toJsonString(objectResult);}
- 使用 @ControllerAdvice,不用任何的配置,只要把这个类放在项目中,Spring能扫描到的地方。但是@ExceptionHandler方法如果返回string类型,注解的类同时也要用@ResponseBody注解,否则就会就会去找string值指向的页面,找不到就会报404错误
@ControllerAdvice
public class ExceptionsHandler {@ExceptionHandler(MaxUploadSizeExceededException.class)//方法返回string类型时,ResponseBody 注解一定要加,否则就会报上面的404错误@ResponseBodypublic String handleException(MaxUploadSizeExceededException ex) {ObjectResult objectResult = new ObjectResult(false);objectResult.setMessage("文件应不大于 "+ getFileKB(ex.getMaxUploadSize()));return JsonUtil.toJsonString(objectResult);}
- 使用@RestControllerAdvice 注解controller类,那异常捕捉方法就不用@ResponseBody注解了
@RestControllerAdvice
public class ExceptionsHandler {@ExceptionHandler(MaxUploadSizeExceededException.class)public String handleException(MaxUploadSizeExceededException ex) {ObjectResult objectResult = new ObjectResult(false);objectResult.setMessage("文件应不大于 "+ getFileKB(ex.getMaxUploadSize()));return JsonUtil.toJsonString(objectResult);}private String getFileKB(long byteFile){if(byteFile==0){return "0KB";}long kb=1024;return ""+byteFile/kb+"KB";}
}
@RestControllerAdvice的源码派生了@ControllerAdvice和@ResponseBody
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ControllerAdvice
@ResponseBody
public @interface RestControllerAdvice {/*** Alias for the {@link #basePackages} attribute.* <p>Allows for more concise annotation declarations e.g.:* {@code @ControllerAdvice("org.my.pkg")} is equivalent to* {@code @ControllerAdvice(basePackages="org.my.pkg")}.* @see #basePackages()*/@AliasFor("basePackages")String[] value() default {};/*** Array of base packages.* <p>Controllers that belong to those base packages or sub-packages thereof* will be included, e.g.: {@code @ControllerAdvice(basePackages="org.my.pkg")}* or {@code @ControllerAdvice(basePackages={"org.my.pkg", "org.my.other.pkg"})}.* <p>{@link #value} is an alias for this attribute, simply allowing for* more concise use of the annotation.* <p>Also consider using {@link #basePackageClasses()} as a type-safe* alternative to String-based package names.*/@AliasFor("value")String[] basePackages() default {};/*** Type-safe alternative to {@link #value()} for specifying the packages* to select Controllers to be assisted by the {@code @ControllerAdvice}* annotated class.* <p>Consider creating a special no-op marker class or interface in each package* that serves no purpose other than being referenced by this attribute.*/Class<?>[] basePackageClasses() default {};/*** Array of classes.* <p>Controllers that are assignable to at least one of the given types* will be assisted by the {@code @ControllerAdvice} annotated class.*/Class<?>[] assignableTypes() default {};/*** Array of annotations.* <p>Controllers that are annotated with this/one of those annotation(s)* will be assisted by the {@code @ControllerAdvice} annotated class.* <p>Consider creating a special annotation or use a predefined one,* like {@link RestController @RestController}.*/Class<? extends Annotation>[] annotations() default {};}
- 第四种捕捉异常后指向一个页面, 这里的controller是直接用@Controller注解的
@Controller public class AccessController { @ExceptionHandler(RuntimeException.class) public String runtimeExceptionHandler(RuntimeException runtimeException, ModelMap modelMap) { logger.error(runtimeException.getLocalizedMessage()); modelMap.put("status", IntegralConstant.FAIL_STATUS); return "exception"; } }
这篇关于controller 异常统一处理的四种方式,透过这四种方式看spring注解的派生性的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!