c# - Angular:无法通过 HttpResponse 返回自定义错误消息
问题描述
当我们在控制器操作中返回错误文本作为ActionResult
/JsonResult
或使用HttpRequest
如下方法时,我一直在谷歌搜索解决方法并查看示例
HttpContext.Current.Response.Status = "error text";
对于我使用的后端应用程序ASP.NET Core 2.1.1
,课程.Status
中缺少属性HttpResponse
。
此外,我找不到任何可能包含我的自定义错误消息的属性。
我使用中间件类来获取异常描述并将其传递为JSON
Startup.cs
app.UseMiddleware<ExceptionHandleMiddleware>();
班级本身
public class ExceptionHandleMiddleware
{
private readonly RequestDelegate next;
public ExceptionHandleMiddleware(RequestDelegate next)
{
this.next = next ?? throw new ArgumentNullException(nameof(next));
}
public async Task Invoke(HttpContext context)
{
try
{
await next(context);
}
catch (Exception ex)
{
context.Response.Clear();
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
context.Response.ContentType = "application/json";
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
await context.Response.WriteAsync(JsonConvert.SerializeObject(new { error = $"{ex.GetType().FullName}: '{ex.Message}'" }));
}
}
}
看看线
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
这是必需的,因为在我使用的Angular 6 应用程序HttpInterceptor
中,为了捕获错误,您应该返回 HTTP 错误(否则.catch(...)
不会在 Angular 拦截器中触发该块)。
这是我的 Angular 应用程序中的一点
@Injectable()
export class ErrorHandlerInterceptor implements HttpInterceptor {
constructor(
private notify: NgNotify,
) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next
.handle(req)
.catch(this.handleError)
}
...
尽管context.Response.WriteAsync(...)
bit确实返回了异常文本,但我无法在.catch(...)
拦截器块中提取它。
public handleError = (error: Response) => {
这里error
打印为(请注意,它缺少“Last Entry”JSON
的错误消息)
{
"headers":{
"normalizedNames":{
},
"lazyUpdate":null
},
"status":500,
"statusText":"OK",
"url":"https://localhost:44305/api/Entry/GetNext?id=11962",
"ok":false,
"name":"HttpErrorResponse",
"message":"Http failure response for https://localhost:44305/api/Entry/GetNext?id=11962: 500 OK",
"error":{
}
}
不过,如果我打开 chrome 的网络选项卡,我可以看到以下内容
所以,我似乎无法从error: Response
.
也许,有人知道将错误传递给 Angular 客户端并在那里获取它的更好方法?
更新 1 - 错误处理程序(我只是将断点放在那里以调查错误的内容)
public handleError = (error: Response) => {
debugger
return Observable.throw(error)
}
解决方案
我的疏忽。
如果您查看返回的 JSON
....
"message":"Http failure response for https://localhost:44305/api/Entry/GetNext?id=11962: 500 OK",
"error":{
}
}
error
似乎是一个空对象
事实上error
,Blob
我们应该按照以下方式阅读
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next
.handle(req)
.catch(this.handleError)
}
public handleError = (error: Response) => {
let reader = new FileReader();
let ngNotify = this._ngNotify;
reader.onload = function () {
var result = JSON.parse(this.result);
ngNotify.nofity('Error', result.error);
};
reader.readAsText(error['error']);
return Observable.throw(error)
}
就是这样。
推荐阅读
- c# - C# 操作从 CSV 解析的数据
- javascript - 多滑块功能
- axios - 在 Axios 中收到 400 个错误请求,但 Postman 状态为 200
- python - 如何使我的精灵图像背景显示为透明?
- powershell - Linter 为正确的 powershell 脚本显示错误 SC1036
- reactjs - 我可以映射两个数组以使两者都渲染到同一个卡片组件吗?
- excel - 如何在 VBA 中进行转置数组?
- python - 如何解决 Python OSMNX 错误信息:TypeError: unhashable type: 'dict'
- javascript - 在nodejs中渲染灰尘模板的问题
- java - 在 Firestore 中保存 Jsonified Java 对象