0


关于java运行中抛出异常的几种写法

1.

@Override
public PageInfo<Map<String, Object>> selectPage(Integer page, Integer size) {
    PageHelper.startPage(page,size);
   List<Map<String,Object>> list= dictMapper.selectPage1();
   if (list.size()>0){
       throw new IllegalArgumentException("请输入正确代码表,要求表名前缀是:"+"666"+"、");
           //throw new GuliException(20001,"哈哈哈哈");

   }
   return new PageInfo<>(list);
}

1.1postman运行结果

** 2.比较优雅的抛出异常**

package com.atguigu.yygh.cmn.service.impl;

import com.atguigu.yygh.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    //自定义异常
    @ExceptionHandler(GuliException.class)
    @ResponseBody //为了返回数据
    public Result error(GuliException e) {
        log.error(e.getMessage());
        e.printStackTrace();

        return Result.fail(e.getCode()).message(e.getMsg());
    }

}

package com.atguigu.yygh.cmn.service.impl;

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

@Data
@AllArgsConstructor  //生成有参数构造方法
@NoArgsConstructor   //生成无参数构造
public class GuliException extends RuntimeException {
    private Integer code;//状态码
    private String msg;//异常信息
}

@Override
public PageInfo<Map<String, Object>> selectPage(Integer page, Integer size) {
    PageHelper.startPage(page,size);
   List<Map<String,Object>> list= dictMapper.selectPage1();
   if (list.size()>0){
       //throw new IllegalArgumentException("请输入正确代码表,要求表名前缀是:"+"666"+"、");
           throw new GuliException(20001,"哈哈哈哈");

   }
   return new PageInfo<>(list);
}

postman测试结果


本文转载自: https://blog.csdn.net/weixin_61503139/article/details/126602679
版权归原作者 Harbor Lau 所有, 如有侵权,请联系我们删除。

“关于java运行中抛出异常的几种写法”的评论:

还没有评论