弹簧引导自定义返回错误码错误信息的方法

  介绍

这篇文章主要介绍了弹簧引导自定义返回错误码错误信息的方法,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获、下面让小编带着大家一起了解一下。

<强>,说明

?在实际的开发过程中,很多时候要定义符合自己业务的错误码和错误信息,而不是统一的而不是统一的下面这种格式返回到调用端

INTERNAL_SERVER_ERROR(500年,“Internal  Server  Error"),

下面我们来看看如何将我们自定义的错误码和错误信息返回到调用端。

<强> 1自定义错误码

?首先我们要定义一个枚举类

public  enum  ErrorEnum  {   ,/*   ,,*,错误信息   ,,*,*/E_20011才能(20011,“缺少必填参数“),   ,,,   private 才能Integer 错误代码;   private 才能;String  errorMsg;   ErrorEnum才能(Integer  errorCode, String  errorMsg), {   ,,,this.errorCode =,错误代码;   ,,,this.errorMsg =, errorMsg;   ,,}   public 才能;Integer  getErrorCode (), {   ,,,return 错误代码;   ,,}   public 才能;String  getErrorMsg (), {   ,,,return  errorMsg;   以前,,}

<强> 2定义一个异常类

?定义一个异常类继承RuntimeException类

public  class  BusinessException  extends  RuntimeException  {   private 才能static  final  long  serialVersionUID =, 1 l;   private 才能;Integer 代码;   ,/* *   ,,*,@param  errorEnum 以错误的ErrorEnum做参数   ,,*/public 才能;BusinessException (ErrorEnum  errorEnum), {   ,,,超级(errorEnum.getErrorMsg ());   ,,,this.code =, errorEnum.getErrorCode ();   ,,,this.resultJson =, CommonUtil.errorJson (errorEnum);   ,,}   public 才能;Integer  getCode (), {   ,,,return 代码;   ,,}   public 才能;void  setCode (Integer 代码),{   ,,,this.code =,代码;   ,,}   }

<强> 3定义一个异常返回的模板类

?模板类定义了如何将异常通过什么形式进行返回。

public  class  ExceptionResponse  {   private 才能;String 信息;   private 才能;Integer 代码;   public 才能;ExceptionResponse (Integer 代码,String 消息),{   ,,,this.message =,消息;   ,,,this.code =,代码;   ,,}   public 才能;static  ExceptionResponse 创建(Integer 代码,String 消息),{   ,,,return  new  ExceptionResponse(代码,,消息);   ,,}   public 才能;Integer  getCode (), {   ,,,return 代码;   ,,}   public 才能;String  getMessage (), {   ,,,return 信息;   ,,}   }

<强> 4定义全局处理控制器层异常

@ControllerAdvice   @Slf4j   public  class  ExceptionHandler  {      @ResponseBody才能   @ResponseStatus才能(HttpStatus.INTERNAL_SERVER_ERROR)   @ExceptionHandler才能(Exception.class)   public 才能;ExceptionResponse  handleException (Exception 交货),{   ,,,if  (ex  instanceof  BusinessException), {   ,,,,,log.warn (ex.getMessage(),交货);   ,,,,,BusinessException  BusinessException =, (BusinessException),交货;   ,,,,,return  ExceptionResponse.create (businessException.getCode (),, businessException.getMessage ());   ,,,},{else    ,,,,,log.error (ex.getMessage(),交货);   ,,,,,return  ExceptionResponse.create (HttpStatus.INTERNAL_SERVER_ERROR.value (),, ex.getMessage ());   ,,,}   ,,}   }

<强> 5演示效果

?定义控制器层

@PostMapping(“测试/exception")   public 才能;String  testException (), {   ,,,throw  new  BusinessException (ErrorEnum.E_20011);   以前,,}

?通过邮递员调用返回结果为

{,“message":,“缺少必填参数,,,“code":, 20011,}

感谢你能够认真阅读完这篇文章,希望小编分享的“春引导自定义返回错误码错误信息的方法”这篇文章对大家有帮助,同时也希望大家多多支持,关注行业资讯频道,更多相关知识等着你来学习!

弹簧引导自定义返回错误码错误信息的方法