spring自定义异常处理,前端接收抛出结果

  • 1、首先创建CustomException继承RuntimeException,使用时可以throw抛出
public class CustomException extends RuntimeException{

	private Integer code;
	private String message;
	
	public CustomException(Integer code, String message) {
		super();
		this.code = code;
		this.message = message;
	}

	//get/set
	
}
  • 2、然后创建ExceptionController(注解@RestControllerAdvice),并添加handleCustomException方法(注解@ExceptionHandler),使CustomException异常抛出使调用该函数,并把结果以JSON形式返回到响应体中(注解@ResponseBody)
@RestControllerAdvice
public class ExceptionController {

	//抛出CustomException时,handleCustomException被调用
	@ExceptionHandler(CustomException.class)
	@ResponseBody
	public CommonResult<Message> handleCustomException(CustomException ex,HttpServletRequest request,HttpServletResponse response){
		
		//放入响应头中
//		response.setStatus(ex.getCode());
//		response.setHeader("Message", ex.getMessage());
		
		//放入响应体中,返回
		return CommonResult.failed(ex.getCode(), Message.createMessage(ex.getMessage()));
	}
	
}
  • 3、使用自定义异常
throw new CustomException(1001, "用户名或密码错误");
  • 4、CommonResult是自己定义的统一返回数据的结果类,前端会接受到结果类转成JSON的数据
    参考之前文章:实现vue项目和springboot项目前后端数据交互
  • 5、使用枚举定义错误码和错误信息
    参考文章

你可能感兴趣的:(Java,spring,前端,java)