首页 技术 正文
技术 2022年11月16日
0 收藏 762 点赞 4,151 浏览 981 个字

对于与数据库相关的 Spring MVC 项目,我们通常会把 事务 配置在 Service层,当数据库操作失败时让 Service 层抛出运行时异常,Spring 事物管理器就会进行回滚。

如此一来,我们的 Controller 层就不得不进行 try-catch Service 层的异常,否则会返回一些不友好的错误信息到客户端。但是,Controller 层每个方法体都写一些模板化的 try-catch 的代码,很难看也难维护,特别是还需要对 Service 层的不同异常进行不同处理的时候。例如以下 Controller 方法代码(非常难看且冗余):

    @PostMapping("/uppic1")
@ResponseBody
public JsonResponse uppic1(@RequestParam("file1") MultipartFile file1) throws Exception {
JsonResponse jr=null;
FastDFSClient client = new FastDFSClient(fdfs_client);
String extName = file1.getOriginalFilename().substring(file1.getOriginalFilename().lastIndexOf(".")+1);
String path = null;
try {
path = client.uploadFile(file1.getBytes(),extName,null);
jr=new JsonResponse(1,"操作成功",file_server+path);
} catch (Exception e) {
jr=new JsonResponse(0,"操作失败",path);
e.printStackTrace();
}
return jr;
}

使用ControllerAdvice :

@ControllerAdvice
public class GlobalExceptionHandler { @ExceptionHandler(Exception.class)
@ResponseBody
JsonResponse handleException(){
JsonResponse jr=new JsonResponse(1,"服务器异常!");
return jr;
}
}

这样所有controller层的异常都会返回这样的提示了。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,907
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,432
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,247
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,058
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,690
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,728