异常处理

异常处理

异常继承结构

注意:受检异常是指在编译时会出现的异常,非受检异常时指在运行过程中因参数或业务逻辑不合理产生的异常。

什么时异常及如果不处理会又什么影响

什么时异常

异常是在程序中导致程序中断的运行的一种指令流。分为错误、和异常。错误是编码规则错误,而异常时在编译或执行的过程中会出现不符合逻辑的错误。

如果不处理的影响

如果产生的异常不处理,则会导致程序中断,即JVM自动停止当前运行程序。

异常如何处理

格式

格式1 

// 将异常抛出,由调用者进行处理
public void demo() throws Exception{
       
}

 格式2

  // 异常自身处理
  try{
    
        // 可能会出现异常的代码块

    }catch (IOException i){ // 异常分类处理 格式:异常名称  对象名
       
         // 异常处理
        
    }catch (Exception e | DataFormatException d){ // 不同异常的相同处理
        
         // 异常处理
       
    }finally {
            
        // 默认执行代码块 该代码块可以被省略不写,但是常用于资源释放的同意处理
            
        // 改代码块始终会执行,只有一种情况该代码块不会执行,JVM 停止运行时该代码块不会执行
        
    }

throw 关键字

public void demo(){
    int age = 200;

    if (age < 0 | age > 150) {
        // 通过 throw 关键字将异常抛出
        throw new Exception("异常信息提示");
    }
}

项目中如何使用自定义异常并且进行自定义异常拦截 @ControllerAdvice和@ExceptionHandler结合使用

结果集:

package com.asiait.health.common;

import com.asiait.health.common.enumeration.ResultStatus;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;

/**
 * 返回结果封装类
 * @author A&S wjy
 * @param <T>
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Result<T> implements Serializable {

    /**
     * 响应状态码
     */
    private int code;

    /**
     * 响应信息
     */
    private String msg;

    /**
     * 响应数据
     */
    private T data;

    public Result() {
    }

    public int getCode() {
        return code;
    }

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

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

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

    public Result(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Result(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public Result(T data) {
        this.data = data;
    }

    /**
     * 返回成功的状态,不需要向前台传递data时
     * @return 返回结果
     */
    public static Result success(){
        return new Result(ResultStatus.SUCCESS.getStatus(),ResultStatus.SUCCESS.getResponsePhrase());
    }

    /**
     * 成功后需要返回的状态
     * @param data
     * @return
     */
    public static Result success(Object data){
        return new Result(ResultStatus.SUCCESS.getStatus(),ResultStatus.SUCCESS.getResponsePhrase(),data);
    }

    /**
     * 返回失败的封装类型
     * @param status 错误码
     * @return
     */
    public static Result error(int status){
        return new Result(status,ResultStatus.getResponsePhrase(status));
    }

    /**
     * 自定义错误返回信息类型
     * @param status 状态码
     * @param msg 错误信息
     * @return
     */
    public static Result error(int status,String msg){
        return new Result(status,msg);
    }

}

 自定义异常

package com.asiait.health.common.errors;

/**
 * 参数获取异常类
 * @author A&S wjy
 * @description
 * @date 2019/12/28 16:39
 */
public class ParamCatchException extends RuntimeException { // 继承 RuntimeException 即可

    private String message;

    public ParamCatchException() {
    }

    public ParamCatchException(String message) {
        super(message);
        this.message = message;
    }
}

 全局异常拦截

package com.asiait.health.common.errors;

import com.asiait.health.common.Result;
import com.asiait.health.common.enumeration.ResultStatus;
import com.github.binarywang.wxpay.exception.WxPayException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 异常信息拦截类
 * @author A&S wjy
 */
@ControllerAdvice // springMVC 全局异常拦截  与 @ExceptionHandler 结合使用
@ResponseBody
public class ExceptionTranslator {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionTranslator.class);

    
    @ExceptionHandler(StandardsCalculateException.class)
    public Result standardsCalculateException(StandardsCalculateException ex){
        logger.error("体脂秤标准计算异常" + ex.getMessage() + ":{}", ex);
        return            Result.error(ResultStatus.STANDARDS_CALCULATE_ERROR.getStatus(),ex.getMessage());
    }
}

使用

public class Demo{

    public void demo(int b){

        int a = 10;
        
        if (a < b){
            throw new ParamCatchException("异常信息");
        }
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值