龙空技术网

SpringBoot:全局异常处理

前进D蜗牛 304

前言:

现时各位老铁们对“mapput空指针异常”大致比较讲究,姐妹们都需要学习一些“mapput空指针异常”的相关知识。那么小编也在网摘上网罗了一些对于“mapput空指针异常””的相关资讯,希望你们能喜欢,各位老铁们一起来了解一下吧!

什么是异常

异常是我们在设计的程序在执行过程中进入到我们没有预料到的情况而返回的结果,在我们的应用中,异常一般分为两类:

1 非法的请求或者访问的资源不存在时不能对请求进行正常的响应,如访问访问一个不存在的页面时会报404;

2 由于程序的设计有误导致的在执行期间发生错误,如空指针异常;

为什么要处理异常

当我们使用浏览器或者其他的工具发起请求时,如果服务不能正常的响应,就会导致用户的体验不好。

创建controller和service:

@Controller@RequestMapping("/exce")public class ExceptionController {    @Autowired    private TestService testService;    @GetMapping("/test")    public String test() throws Exception {        int result = testService.save();        return "/success.html";    }}
@Servicepublic class TestService {    public Integer save() throws Exception {        //do some thing        Integer result = 100 / 0;//生成异常        return result;    }}

请求上边的服务,服务内部发生异常而没有做任何处理时,会返回:

因此针对各种情况进行对应的响应还是很重要的。

异常处理的实现

1 访问资源不存在的异常,我们可以通过实现ErrorController接口实现,如下:

@Controllerpublic class MyErrorController implements ErrorController {    @RequestMapping("/error")    public String handlerError(HttpServletRequest request){        //获取错误的状态码        String errorPage = "";        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");        //根据状态码返回对应的页面        if(statusCode == 400){            errorPage = "/400.html";        }else if(statusCode == 403){            errorPage = "/403.html";        }else if(statusCode == 500){            errorPage = "/500.html";        }else{            errorPage = "/404.html";        }        return errorPage;    }    @Override    public String getErrorPath() {        return "/error";    }}

创建错误对应的页面,如500.html:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>error-500</title></head><body><span>500-服务走丢了,请稍后重试!</span></body></html>

这样当请求发生错误转向/error请求时,会执行我们对应的逻辑并返回。如下:

当然了,在如上的方法中,如果我们要返回一个JSON对象信息,我们可以在方法上加入@ResponseBody注解来实现。

2 在请求执行过程中发生错误的异常,我们可以通过@ControllerAdvice控制器建议注解配合@ExceptionHandler注解来实现,比如我们创建一个全局的异常处理类,如下:

@ControllerAdvicepublic class GlobalExceptionHandler {    @ExceptionHandler(value = Exception.class)//处理对应的异常类    @ResponseBody    public Object handlerException(HttpServletRequest request, Exception e) {        Map<String, String> map = new HashMap<String, String>();        map.put("code", "500");        map.put("msg", e.getMessage());        return map;    }}

请求服务,返回:

在项目中,我们一般都会根据业务定义异常,如下:

public class BusinessException extends RuntimeException {    private String code;    public BusinessException(String code, String msg) {        super(msg);        this.code = code;    }    // 省略get 和set 方法}

针对自定义的异常,我们只需要在在全局异常处理类中添加处理当前异常的方法即可,如:

@ExceptionHandler(value = BusinessException.class)@ResponseBodypublic Object handlerBusinessException(HttpServletRequest request, BusinessException e) {    Map<String, String> map = new HashMap<String, String>();    map.put("code", "500");    //为了区别上边的Exception异常,添加BusinessException输出    map.put("msg", "BusinessException:"+e.getMessage());    return map;}

修改Controller 中抛出的异常为自定义异常,如下:

@RestController@RequestMapping("/exce")public class ExceptionController {    @Autowired    private TestService testService;    @GetMapping("/test")    public String test() {        try {            int result = testService.save();        } catch (Exception e) {            //抛出自定义的异常            throw new BusinessException("500", e.getMessage());        }        return "success";    }}

请求服务,返回:

点击关注,后期更多精彩内容呈上!

标签: #mapput空指针异常