服务器端错误处理与角形 [英] Server side errors handling with angular-formly
问题描述
我正在寻找有关如何显示服务器响应的错误的解决方案,这是对每个无效提交的响应,因此我想在应用程序级别而不是在控制器中创建错误处理程序.我想同时在FORM级别和字段级别上显示错误.
I'm looking for solution on how I can display errors that the server respond, this is the respond for every invalid submission so I want to make the error handler in the app level and not in a controller. I want to display the errors both on the FORM level and on the field level.
我有一个REST API,如果发生错误,它将返回以下JSON对象:
I have a REST API that in case of error return the following JSON object:
{
"message": "Validation error: Validation notEmpty failed,\nValidation error: Validation isEmail failed",
"errors": [
{
"field": "username",
"message": "Validation notEmpty failed"
},
{
"field": "email",
"message": "Validation isEmail failed"
}
]
}
如果有任何错误,如何创建显示错误的服务?
How can I create a service that display the errors in case there is any?
谢谢
推荐答案
所以,我为另一个答案创建了这个.让我知道这种设置是否适合您.在此,单击按钮后,错误将在服务器的响应上显示.您可以相应地对其进行修改.
So, i created this for another answer. Let me know if this sort of a setup works for you. Here, the error is intended to be displayed on response from the server after button click. You can modify it accordingly.
我为该字段提供了一个自定义模板,如下所示:
I have given the field a custom template as follows:
formlyConfigProvider.setWrapper({
name: 'inputWrapper',
template: '<div ng-class="to.changeColor==\'red\'? \'redBorder\' : \'otherBorder\'"><formly-transclude></formly-transclude>{{to.keyVal}}</div>'
});
表单元素是通过模式格式定义的,以允许分别访问每个元素.
The form elements are defined through a schema format to allow each element to be individually accessed.
vm.schema={
"schema": {
"coolValue" : [{
"key": "coolValue",
"type": "input",
"wrapper": ['inputWrapper'],
"templateOptions": {
"type" : "text",
"label": 'Cool Value',
"keyVal":"",
"changeColor":"green"
}
}]
}
};
最后, onSubmit
函数
function onSubmit() {
//Do whatever you want here
//Let's say your server returns an error "iNVALID Credentials"
var response={
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization",
}
],
"code": 401,
"message": "Invalid Credentials"
}
};
vm.schema.schema.coolValue[0].templateOptions.changeColor="red";
vm.schema.schema.coolValue[0].templateOptions.keyVal=response.error.message;
}
});
您基本上可以在此处传递来自服务器的任何错误消息或响应.
You can essentially pass any error message or response from the server here.
CSS包含一个用于在字段中添加红色 border
的类.您可以随意禁用此功能.如果在此区域也需要使用ping功能,则可以ping通.
The CSS contains a class to add a red border
to the field.You are free to disable this.Feel free to ping if you need anything in this area as well.
这是 演示
这篇关于服务器端错误处理与角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!