我是靠谱客的博主 听话翅膀,这篇文章主要介绍Spring Boot 统一异常处理的案例,现在分享给大家,希望可以做个参考。

统一异常处理:统一处理程序中抛出的所有或特定异常.

1.返回页面的数据类型为:Json格式

package com.example.demo.error;

/**
 * Create by szw on 2017/11/29 16:31
 */
public class ErrorInfo<T> {
    public static final Integer OK = 0;
    public static final Integer ERROR = 100;

    private Integer code;
    private String message;
    private T data;

    public static Integer getOK() {
        return OK;
    }

    public static Integer getERROR() {
        return ERROR;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

2.自定义异常类

package com.example.demo.exception;

import sun.plugin2.message.Message;

/**
 * Create by szw on 2017/11/29 16:32
 */
public class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

3.统一异常处理

package com.example.demo.exception;

/**
 * Create by szw on 2017/11/29 15:59
 */

import com.example.demo.error.ErrorInfo;
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 javax.servlet.http.HttpServletRequest;

/**
 * 统一异常处理
 */
@ControllerAdvice
class GlobalExceptionHandler {
    public static final String DEFAULT_ERROR_VIEW = "error";
    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public ErrorInfo defaultErrorHandler(HttpServletRequest req, MyException e) throws Exception {
        ErrorInfo<String> stringErrorInfo = new ErrorInfo<>();
        stringErrorInfo.setMessage(e.getMessage());
        stringErrorInfo.setCode(ErrorInfo.ERROR);
        stringErrorInfo.setData("some date");
        return stringErrorInfo;
    }
}

最后

以上就是听话翅膀最近收集整理的关于Spring Boot 统一异常处理的案例的全部内容,更多相关Spring内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(47)

评论列表共有 0 条评论

立即
投稿
返回
顶部