首先我们需要创建一个我们自定义的Exception类
package com.atguigu.springboot.exception;
public class UserNotExistException extends RuntimeException {
public UserNotExistException() {
super("用户不存在");
}
}
然后我们再自定义一个MyErrorAttributes类继承DefaultErrorAttributes类,将其加入到容器中替换SpringBoot默认的Attribute类
package com.atguigu.springboot.component;
import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import java.util.Map;
//给容器中加入我们自己定义的ErrorAttributes
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
//返回值的map就是页面和json能获取的所有字段
@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace);
map.put("company","atguigu");
//我们的异常处理器携带的数据
Map<String,Object> ext = (Map<String, Object>) requestAttributes.getAttribute("ext", 0);
map.put("ext",ext);
return map;
}
}
然后再创建一个handler类对补货的异常进行处理
package com.atguigu.springboot.controller;
import com.atguigu.springboot.exception.UserNotExistException;
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;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class MyExceptionHandler {
//1、浏览器客户端返回的都是json
// @ResponseBody
// @ExceptionHandler(UserNotExistException.class)
// public Map<String,Object> handleException(Exception e){
// Map<String,Object> map = new HashMap<>();
// map.put("code","user.notexist");
// map.put("message",e.getMessage());
// return map;
// }
@ExceptionHandler(UserNotExistException.class)
public String handleException(Exception e, HttpServletRequest request){
Map<String,Object> map = new HashMap<>();
//传入我们自己的错误状态码 4xx 5xx
/**
* Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
*/
request.setAttribute("javax.servlet.error.status_code",500);
map.put("code","user.notexist");
map.put("message","用户出错啦");
request.setAttribute("ext",map);
//转发到/error
return "forward:/error";
}
}
我们在controller中throw一个自定义的异常
@ResponseBody
@RequestMapping("/hello")
public String hello(@RequestParam("user") String user){
if(user.equals("aaa")){
throw new UserNotExistException();
}
return "Hello World";
}
这样我们就完成了一个自定义的异常处理啦!