栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

全局异常处理

Java 更新时间:发布时间: 百科书网 趣学号

阿松大

构架截图

 result.java

package com.qgx.demo.common;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;


@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {

    private String code;
    private String msg;
    private Object data;

    public static Result success() {
        return new Result(Constants.CODE_200, "", null);
    }

    public static Result success(Object data) {
        return new Result(Constants.CODE_200, "", data);
    }

    public static Result error(String code, String msg) {
        return new Result(code, msg, null);
    }

    public static Result error() {
        return new Result(Constants.CODE_500, "系统错误", null);
    }

}

Constants.java(常量类,定义Code) 接口

package com.qgx.demo.common;


public interface Constants {
    String CODE_200 = "200"; //成功
    String CODE_401 = "401";  // 权限不足
    String CODE_400 = "400";  // 参数错误
    String CODE_500 = "500"; // 系统错误
    String CODE_600 = "600"; // 其他业务异常
    String Session_key="";
}

GlobalExceptionHandler.java

package com.qgx.demo.exception;

import com.qgx.demo.common.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


@ControllerAdvice
public class GlobalExceptionHandler {
    
    //ExceptionHandler 统一处理某一类异常
    @ExceptionHandler(value = ServiceException.class)
    @ResponseBody
    public Result handle(ServiceException se){
        return Result.error(se.getCode(), se.getMessage());
    }
}

ServiceException.java(自定义业务异常)

package com.qgx.demo.exception;

import lombok.Getter;


@Getter
    public class ServiceException extends RuntimeException{
        private String code;

        public ServiceException(String code, String msg) {
            super(msg);
            this.code = code;
        }
}

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/888774.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号