美文网首页Spring Boot实践记录
SpringBoot配置异常处理类

SpringBoot配置异常处理类

作者: Chinesszz | 来源:发表于2017-02-08 10:27 被阅读49次

    首先定义一个异常

    public class MyException extends Exception {
        public MyException(String message) {
            super(message);
        }
    }
    

    当在control类中throw此异常

    @Controller
    public class HelloController {
        @RequestMapping("/json")
        public String json() throws MyException {
            throw new MyException("发生错误2");
        }
    }
    

    处理该异常

    @ControllerAdvice
    public class GlobalExceptionHandler {
        @ExceptionHandler(value = MyException.class) //这个注解,接受异常
        @ResponseBody //返回json
        public ErrorInfo<String> jsonErrorHandler(HttpServletRequest req, MyException e) throws Exception {
            ErrorInfo<String> r = new ErrorInfo<>();
            r.setMessage(e.getMessage());
            r.setCode(ErrorInfo.ERROR);
            r.setData("Some Data");
            r.setUrl(req.getRequestURL().toString());
            return r;
        }
    }
    
    应用启动:响应
    
    {
        code: 100,
        data: "Some Data",
        message: "发生错误2",
        url: "http://localhost:8080/json"
    }
    

    相关文章

      网友评论

        本文标题:SpringBoot配置异常处理类

        本文链接:https://www.haomeiwen.com/subject/nesvittx.html