我对我们向客户返回错误的方式感到担忧.
当我们收到错误时,我们通过抛出HttpResponseException立即返回错误:
public void Post(Customer customer)
{
if (string.IsNullOrEmpty(customer.Name))
{
throw new HttpResponseException("Customer Name cannot be empty", HttpStatusCode.BadRequest)
}
if (customer.Accounts.Count == 0)
{
throw new HttpResponseException("Customer does not have any account", HttpStatusCode.BadRequest)
}
}
Run Code Online (Sandbox Code Playgroud)
或者我们累积所有错误然后发送回客户端:
public void Post(Customer customer)
{
List<string> errors = new List<string>();
if (string.IsNullOrEmpty(customer.Name))
{
errors.Add("Customer Name cannot be empty");
}
if (customer.Accounts.Count == 0)
{
errors.Add("Customer does not have any account");
}
var responseMessage = new HttpResponseMessage<List<string>>(errors, HttpStatusCode.BadRequest);
throw new HttpResponseException(responseMessage);
}
Run Code Online (Sandbox Code Playgroud)
这只是一个示例代码,无论是验证错误还是服务器错误都无关紧要,我只想了解最佳实践,每种方法的优缺点.
我正在使用WebAPI 2中的服务,端点当前返回一个IHttpActionResult.我想返回一个状态代码422,但因为它不在HttpStatusCode枚举中,所以我不知道如何发送它,因为所有的构造函数都需要一个参数HttpStatusCode
现在,我正在回归BadResult(message),但返回422+消息对我的客户来说会更具描述性和实用性.有任何想法吗?
我有一个Angular 6客户端,它使用通过.Net Web Api开发的REST Api。
除错误处理外,其他所有东西都在工作。当我尝试处理错误以对不同的状态码(404、403、409、500 ...)做出不同反应时,我简直无法使其正常工作。HttpErrorResponse对象没有应假定的任何字段(例如“状态”或“错误”)。
我提供了一个超级简单的服务来重现该问题:
在service.ts上请求
public test(): Observable<any> {
let url = this.templatesUrl + '/myMethod';
console.log('GET myMethod ' + url);
return this.http.get<any>(url)
.pipe(catchError(this.handleError));
}
Run Code Online (Sandbox Code Playgroud)
错误处理程序(与官方文档相当直接):
private handleError(error: HttpErrorResponse) {
console.warn(error);
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code …Run Code Online (Sandbox Code Playgroud)