springboot异常处理

20 篇文章 0 订阅
7 篇文章 0 订阅

一 ,传统的处理异常 那种标准的try.....catch   

try {
    ...
} catch (Exception e) {
    doSomeThing();
}

像这种标准的 try-catch 是可以解决问题,但如果让你在每个接口实现里面都 try-catch 一下,我想你应该是不太愿意的,而且太麻烦。那么下面来介绍下 SpringBoot 为我们提供的处理方式。


二 ExceptionHandler类处理异常

1.单一Controller内处理异常,直接在对应的 Controller 里面增加一个异常处理的方法,并使用 @ExceptionHandler 标识它即

example:

@RestController
public class UserController {
	
	@Autowired
	private UserMapper userMapper;
	
	@RequestMapping("/getUsers")
	public List<User> getUsers() {
		List<User> users=userMapper.getAll();
		return users;
	}
	
	@ExceptionHandler //处理所有异常
	@ResponseBody
	public Result runtimeExceptionHandler(RuntimeException e,
			HttpServletRequest req, HttpServletResponse resp) throws Exception {
		System.out.println(req.getParameter("username"));
		e.printStackTrace();
		System.out.println(e.getMessage());
		return new Result("-1", "系统运行异常");
	}
	
    @RequestMapping("/getUser")
    public User getUser(Integer id) {
    	User user=userMapper.getOne(id);
        return user;
    }
    
    @RequestMapping("/add")
    public void save(User user) {
    	userMapper.insert(user);
    }

上面异常会在当前Controller内的生效

2 父类Controller异常处理 定义BaseController 

public class BaseController {

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        e.printStackTrace();
        return new Result(ResultCode.WEAK_NET_WORK);
    }

}
UserController 通过继承 BaseController 完成异常处理:


@RestController
public class UserController extends BaseController {
    ...
}

3,全局异常处理 @ControllerAdvice

package com.kerry.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常类
 * 
 * @author Administrator
 *
 */
@ControllerAdvice
public class GolbalExceptionHandler {

	@ExceptionHandler(RuntimeException.class)
	// @ExceptionHandler(value={RuntimeException.class,MyRuntimeException.class})
	// @ExceptionHandler //处理所有异常
	@ResponseBody
	public Result runtimeExceptionHandler(RuntimeException e,
			HttpServletRequest req, HttpServletResponse resp) throws Exception {
		System.out.println(req.getParameter("username"));
		e.printStackTrace();
		System.out.println(e.getMessage());
		return new Result("-1", "系统运行异常");
	}

	@ExceptionHandler(NullPointerException.class)
	@ResponseBody
	public Result exceptionHandler(NullPointerException e) {
		e.printStackTrace();
		System.out.println(e.getMessage());
		return new Result("-1", "空指针异常");
	}

	public class Result {
		public String code;
		public String msg;

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

}

三,实现ErrorController  全局异常

在springboot项目中调用接口时,出现了异常,但客户端却收到一个相对正常的响应,这是因为 SpringBoot 默认提供了一个 /error 的映射,该映射被注册为 Servlet 容器中的一个全局错误页面用来合理处理所有的异常情况。想要使其满足自己的数据规范,可以自己定义一个新的 ErrorController,代码如下

package com.kerry.exception;

import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局error异常类 SpringBoot 默认提供了一个 /error 的映射,该映射被注册为 Servlet
 * 容器中的一个全局错误页面用来合理处理所有的异常情况。 想要使其满足自己的数据规范,可以自己定义一个新的 ErrorController
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/error")
public class MyErrorController implements ErrorController {

	@Override
	public String getErrorPath() {
		return "/error";
	}

	@RequestMapping
	@ResponseBody
	public String doHandleError() {
		//返回错误信息
		return "this is error msg or page ";
	}

}
使用这种errorController方式后台会打印异常堆栈错误信息

若使用@ControllerAdvice或者在Controller类中使用@ExceptionHandler时候默认是没有异常堆栈信息打印当需要打印时候,需要手动写代码

e.printStackTrace();

	@ExceptionHandler(RuntimeException.class)
	// @ExceptionHandler(value={RuntimeException.class,MyRuntimeException.class})
	// @ExceptionHandler //处理所有异常
	@ResponseBody
	public Result runtimeExceptionHandler(RuntimeException e,
			HttpServletRequest req, HttpServletResponse resp) throws Exception {
		e.printStackTrace();
		System.out.println(e.getMessage());
		return new Result("-1", "系统运行异常");
	}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奔跑的窝窝牛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值