项目经常会遇到一些常见的异常,如:404 ,500,这中错误给客户看到肯定是体验不好的
解决方法:
1 .添加try catch
2编写全局异常处理
本文主要将第二种
首先看下目录结构:
所用到的注解:
@ExceptionHandler 指定捕获的异常类 @ControllerAdvice 扫包 @ResponseBody 不加没法返回的
创建全局错误处理类
这里提供两,一个直接返回json,一个是跳转页面的
package com.cn.demo.error;
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.servlet.ModelAndView;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice(basePackages = "com.cn.demo")
public class error {
//非跳转页面
// @ExceptionHandler(RuntimeException.class)
// @ResponseBody
// public Map<String,Object> errorResult(){
// Map<String,Object> map = new HashMap<String,Object>();
// map.put("errorCode",500);
// map.put("errorMassage","系统错误");
// return map;
// }
//跳转错误页面
//指定捕获的异常类型
@ExceptionHandler(RuntimeException.class)
@ResponseBody
public ModelAndView errorResult(){
ModelAndView view =new ModelAndView();
view.setViewName("error");
return view;
}
}
java类
package com.cn.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class getUser {
@RequestMapping("/User")
public String getUser(int i){
int j=1/i;
return "success";
}
}
测试结果