2017-03-28 69 views
0

首先我使用这个解决方案 - http://www.yiiframework.com/doc-2.0/guide-rest-error-handling.html 但是,我想定制两种类型的错误。Yii2 REST:如何自定义错误响应?

  1. 当模型验证错误。
  2. 当出了问题(Exceptiin)

如果模型验证错误,我得到响应,这样的:

{ 
    "success": false, 
    "data": [ 
     { 
      "field": "country_id", 
      "message": "Country Id cannot be blank." 
     }, 
     { 
      "field": "currency_id", 
      "message": "Currency Id cannot be blank." 
     }, 
     { 
      "field": "originator_id", 
      "message": "Originator Id cannot be blank." 
     } 
    ] 
} 

但我想这样的:

{ 
    "success": false, 
    "data": [ 
"errors": [ 
{ 
      "field": "country_id", 
      "message": "Country Id cannot be blank." 
     }, 
     { 
      "field": "currency_id", 
      "message": "Currency Id cannot be blank." 
     }, 
     { 
      "field": "originator_id", 
      "message": "Originator Id cannot be blank." 
     } 
] 

    ] 
} 

第二类错误我得到

{ 
    "success": false, 
    "data": { 
     "name": "Exception", 
     "message": "Invalid request arguments", 
     "code": 0, 
     "type": "yii\\base\\InvalidParamException",  
     ] 
    } 
} 

但我想:

{ 
    "success": false, 
    "data": { 
     "errors" : 1, <---------------- 
     "name": "Exception", 
     "message": "Invalid request arguments", 
     "code": 0, 
     "type": "yii\\base\\InvalidParamException",  
     ] 
    } 
} 

因为反正用户获得200响应和他们不知道的错误或过失。

+0

如果您使用的是带有错误默认RestController模型送422。 – zakrzu

回答

相关问题