springboot-统一返回数据,自定义异常,异常处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yhhyhhyhhyhh/article/details/84076711

springboot-统一返回数据,统一异常处理,自定义异常

代码下载:
https://github.com/2010yhh/springBoot-demos.git

环境

idea2018,jdk1.8,

springboot版本:1.5.9.RELEASE

1.java异常

Java 提供了两类主要的异常 :runtime exception(预期异常和运行时异常) 和 checked exception (预期异常)

出现运行时异常后,系统会把异常一直往上层抛,一直遇到处理代码。如果没有处理块,到最上层,如果是多线程就由Thread.run() 抛出 ,如果是单线程就被 main() 抛出 。抛出之后,如果是线程,这个线程也就退出了。如果是主程序抛出的异常,那么这整个程序也就退出了。

场景:一般像ssm这种遇到未捕获的异常,不能影响其他的操作,必须处理;

但是:有些场景要求

1.1常见的几种异常

输入输出异常:IOException
算术异常类:ArithmeticExecption
空指针异常类:NullPointerException
类型强制转换异常:ClassCastException

操作数据库异常:SQLException

文件未找到异常:FileNotFoundException
数组负下标异常:NegativeArrayException
数组下标越界异常:ArrayIndexOutOfBoundsException
违背安全原则异常:SecturityException
文件已结束异常:EOFException
字符串转换为数字异常:NumberFormatException
方法未找到异常:NoSuchMethodException

1.2异常的处理

try catch是直接处理,处理完成之后程序继续往下执行,

throw则是将异常抛给它的上一级处理,程序便不往下执行了使用throws继续向上抛出异常

ry catch一般在最上层使用,底层的都使用throws向上抛出。如果即在最上层做try catch,又在底层方法做try catch,程序
会变的很混乱。一般可预见的错误,比如空指针,你完全可以在最上层比如controller层进行判断下,不要让null进入底层方法引起不必要的麻烦,
你也省的给底层和上层方法都加预防空指针异常的判断。

ssm开发中通常:抛出异常后,前端跳转到某个页面或者根据返回的状态码,给出提示操作或者根据状态码做跳转页面

dao层一个抛给service层,service层再抛给Controller层,Controller层catch记录错误信息,

同时controller层返回给前端状态码和错误信息,前端根据状态码做处理:根据状态码显示不同信息,同时将异常作为提示信息显示在前端。

或者:

系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理

1.3统一返回值

public class ResultUtil {
    public static Result success() {
        return success(null);
    }
    public static Result success(Object object) {
        Result result = new Result();
        result.setCode(ResultCode.SUCCESS);
        result.setMsg("成功");
        result.setData(object);
        return result;
    }
    public static Result success(Integer code,Object object) {
        Result result = new Result();
        result.setCode(code);
        result.setMsg("成功");
        result.setData(object);
        return result;
    }

    public static Result error( String msg) {
        Result result = new Result();
        result.setCode(ResultCode.ERROR);
        result.setMsg(msg);
        return result;
    }
    public static Result error(Integer code, String msg) {
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }
}

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/yhhyhhyhhyhh/article/details/84076711
今日推荐