springboot全局异常捕获
有时候在操作数据库的时候会出现异常,处理异常
创建一个全局异常处理类
如:
package com.dahai.springboot;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
// 全局异常捕获
@ControllerAdvice
public class GlobalDefaultExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody // 如果返回String或json要加此注解如果返回界面就不加
public String defaultExceptionHandler(HttpServletRequest req, Exception e) {
System.out.println("有异常啦");
// 返回String
return "对不起服务器繁忙";
// 返回View 创建ModelAndView mv = new ModelAndView("error")
}
}
我们可以自定义异常,比如在请求接口时参数缺失就可以采用抛异常的方式退出,然后在全局异常处理处获取到异常信息返回给客户端
@GetMapping("/findName")
public Demo findDemoByName(String name) throws Exception {
if (name==null || name.length()==0) {
throw new Exception("参数缺失或为空");
}
return demoService.likeName(name);
}
@ExceptionHandler(Exception.class)
@ResponseBody // 如果返回String或json要加此注解如果返回界面就不加
public String defaultExceptionHandler(HttpServletRequest req, Exception e) {
System.out.println("有异常啦"+e.getMessage());
// 返回String
return e.getMessage();
// 返回View 创建ModelAndView mv = new ModelAndView("error")
}