天天看点

Springboot全局捕获异常

以往的ssm架构来说,我们需要在service层定义一个resultMap,如果发成异常去put异常的code和msg信息,没有异常就返回成功的code和msg,然后Controller层去接收resultMap。

现在Springboot出来后我们就可以大大的简化异常处理。

只因有这个注解:

@ControllerAdvice
           
  • 他来了 他来了
  • 他带着 礼物 走来了
  • 他来了 他来了
  • 他脚踏祥云进来了

从此我们的代码处理异常随着他来了变得如此丝滑~

首先我们去写一个code和msg的实体类

package com.qq.weixin.entity;

import lombok.Data;

@Data
public class GlobalException extends RuntimeException {
    String msg;
    String code;

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

}
           

然后我们去写一个带有@ControllerAdvice的Exception处理类

package com.qq.weixin.exception;

import com.qq.weixin.entity.GlobalException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandle {
    @ResponseBody
    @ExceptionHandler(value = GlobalException.class)
    public Map ExceptionHandler(GlobalException ex) {
        Map map = new HashMap();
        map.put("code", ex.getCode());
        map.put("msg", ex.getMsg());
        return map;
    }
}
           

最后我们写一个Controller测试类,去试试这个注解的魅力

package com.qq.weixin.controller;

import com.qq.weixin.entity.GlobalException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;

/**
 * @author XuYangWei
 * @Date 2021/1/20
 */

@RestController
public class TestExceptionController {
    
    @RequestMapping(value = "/test",method= RequestMethod.GET)
    public Map getUserName(@RequestParam String name){
        Map resultMap=new HashMap();
        if(StringUtils.isEmpty(name)){
            throw new GlobalException("9999","名称不能为空");
        }
        resultMap.put("code","0000");
        resultMap.put("msg","处理成功");
        return resultMap;
    }
}
           

效果:

下面我们启动项目后,去请求测试接口。

我们先传递带有name值的参数看看,没有异常的处理结果

Springboot全局捕获异常

然后故意不传递参数name,抛出异常看看效果。

Springboot全局捕获异常

完毕!

下一篇: hello sql