controller 异常统一处理的四种方式,透过这四种方式看spring注解的派生性

本文主要是介绍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);}
  1. 使用 @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);}
  1. 使用@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 {};}
  1. 第四种捕捉异常后指向一个页面, 这里的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注解的派生性的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/932831

相关文章

Spring boot整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap

Linux线程之线程的创建、属性、回收、退出、取消方式

《Linux线程之线程的创建、属性、回收、退出、取消方式》文章总结了线程管理核心知识:线程号唯一、创建方式、属性设置(如分离状态与栈大小)、回收机制(join/detach)、退出方法(返回/pthr... 目录1. 线程号2. 线程的创建3. 线程属性4. 线程的回收5. 线程的退出6. 线程的取消7.

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

golang程序打包成脚本部署到Linux系统方式

《golang程序打包成脚本部署到Linux系统方式》Golang程序通过本地编译(设置GOOS为linux生成无后缀二进制文件),上传至Linux服务器后赋权执行,使用nohup命令实现后台运行,完... 目录本地编译golang程序上传Golang二进制文件到linux服务器总结本地编译Golang程序

Linux下删除乱码文件和目录的实现方式

《Linux下删除乱码文件和目录的实现方式》:本文主要介绍Linux下删除乱码文件和目录的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux下删除乱码文件和目录方法1方法2总结Linux下删除乱码文件和目录方法1使用ls -i命令找到文件或目录

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Linux在线解压jar包的实现方式

《Linux在线解压jar包的实现方式》:本文主要介绍Linux在线解压jar包的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux在线解压jar包解压 jar包的步骤总结Linux在线解压jar包在 Centos 中解压 jar 包可以使用 u

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu