Springboot2 自定义异常处理

 

       开发过程中由于出现异常时想要返返回指定类型的json串,springboot自带的异常处理无法满足需求,自己封装异常处理类进行指定的异常处理。


import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*统一处理拦截
*
*/
@ControllerAdvice//标识为controller异常处理类
public class ControllerExceptionHandler {
	
	@ResponseBody
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//状态码500
	@ExceptionHandler(UserException.class)//指定异常
	public Map<String ,Object> UserNotExitException(UserException ue){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("id", ue.getId());
		map.put("message", ue.getMessage());
		return map;
	}
}

自定义异常处理类

//自定义异常类
public class UserException extends RuntimeException{

	private static final long serialVersionUID = 1L;

	private String id;
	
	private String message;
	
	public UserException(String id, String message) {
		super("this is user exception");
		this.id = id;
		this.message = message;
	}


	public String getId() {
		return id;
	}


	public void setId(String id) {
		this.id = id;
	}


	public String getMessage() {
		return message;
	}


	public void setMessage(String message) {
		this.message = message;
	}
	
	
	
}

运行时异常抛出

@JsonView(User.UserDetailView.class)//json视图处理器,博主下一篇文章解释,可注释掉
	//@RequestMapping(value="/user/{id:\\d+}",method = RequestMethod.GET)//限制id只能为数字
	@GetMapping("/{id:\\d+}")//正则表达式,限制传入内容只能为id
	public User  getInfo(@PathVariable(name="id") String thisId){//获取url中的指定id
		User u = new User();
		u.setUsername("1");
		u.setPassword("11");
		throw new UserException("1","我这出问题了");//抛出指定异常
		//return u;
	}
	

 

总结一下restful风格开发情况下,springboot2异常抛出时捕获处理顺序

controller  -- aspec  --- interceptor---filter

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值