在项目的开发中,如果报错了,直接在页面显示500错误,输出一大堆的异常信息,这对应用户来说体验不友好,所以在企业里面对这些异常一般都会统一捕获,由一个专门的异常处理类来统一处理。
在代码里编写一个处理全局运行异常的类
package com.bjpowernode.handler;
import com.bjpowernode.constants.Constant;
import com.bjpowernode.model.Goods;
import com.bjpowernode.model.ResultObject;
import com.bjpowernode.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
@ControllerAdvice(annotations = {Controller.class, RestController.class}) //可以用来返回统一的错误json或者是统一错误jsp页面
public class GlobalExceptionHandler {
@Autowired
private GoodsService goodsService;
@ExceptionHandler(value = RuntimeException.class)
public @ResponseBody Object errorHandlerByJson (HttpServletRequest request,Exception e) throws Exception{
//拿到异常信息
e.printStackTrace();
System.out.println(goodsService);
Goods goods = goodsService.selectByPrimaryKey(1);
System.out.println(goods.getName());
//可以返回统一数据
return new ResultObject(Constant.ONE,"sorry,服务器开小差了",null);
}
}
这样在前台不会出现错误信息,而是统一的样式。
如果想要发生异常的时候,跳转到统一的错误页,则要在代码里加上ModelAndView
@ExceptionHandler(value = IOException.class)
public ModelAndView errorHandlerByView(HttpServletRequest request, Exception e) throws Exception {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("exception", e.getMessage());
modelAndView.addObject("url", request.getRequestURL());
//设置发生异常的时候,跳转到哪个页面
modelAndView.setViewName("50x");
//可以返回统一数据
return modelAndView;
}
注意:如果这样写,上文出现的代码需要保证IOException只有一种,将另一种方式注释掉。
编写跳转的jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
SpringBoot+MyBatis+JSP
50x
在Controller代码里也可抛出一个异常



