SpringBoot自定义异常

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35706771/article/details/82956126
  1. 进入控制器,抛出异常
	@GetMapping( value = "/exception/{id}")
	public void testException(@PathVariable Integer id) {
		System.out.println("exception");
		throw new UserNotExistException(id);
	}
  1. 自定义异常类
public class UserNotExistException extends RuntimeException{
	private static final long serialVersionUID = 1L;
	private Integer id;
	public UserNotExistException(Integer id) {
		super("User Not Exist sss");
		this.id = id;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
}
  1. 定义异常控制器处理
@ControllerAdvice
public class ControllerExceptionHandle {

	@ExceptionHandler(UserNotExistException.class)
	@ResponseBody
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public Map<String,Object> handleUserNotExistExctption(UserNotExistException ex){
		Map<String,Object> map = new HashMap<String,Object>();
		System.out.println(map);
		map.put("id", ex.getId());
		map.put("message", "ControllerExceptionHandle : UserNotExistException");
		return map;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_35706771/article/details/82956126