SpringBoot自定义异常

  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 handleUserNotExistExctption(UserNotExistException ex){
		Map map = new HashMap();
		System.out.println(map);
		map.put("id", ex.getId());
		map.put("message", "ControllerExceptionHandle : UserNotExistException");
		return map;
	}
}

你可能感兴趣的:(springBoot)