亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Angular:無法通過 HttpResponse 返回自定義錯誤消息

Angular:無法通過 HttpResponse 返回自定義錯誤消息

C#
喵喵時光機 2021-10-31 20:05:40
我一直在谷歌搜索解決方法并看到我們在控制器操作中作為ActionResult/JsonResult或使用HttpRequest如下方法返回錯誤文本時的示例HttpContext.Current.Response.Status = "error text";對于我的后臺應用程序,我使用ASP.NET Core 2.1.1和.Status屬性在缺少HttpResponse類。此外,我找不到任何可能包含我的自定義錯誤消息的屬性。我使用中間件類,它獲取異常描述并將其作為 JSONStartup.csapp.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(...)在攔截器的塊中提取它。所以,我似乎無法從error: Response.也許,有人知道將錯誤傳遞給 Angular 客戶端并在那里獲取它的更好方法?
查看完整描述

2 回答

?
慕桂英3389331

TA貢獻2036條經驗 獲得超8個贊

我的疏忽。


如果您查看返回的 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)

}

就是這樣。


查看完整回答
反對 回復 2021-10-31
?
茅侃侃

TA貢獻1842條經驗 獲得超22個贊

我最終通過實現中間件來攔截HttpResponse、從 blob 中提取錯誤并在 json 中返回消息來解決這個問題。感謝JaapMosselman 的貢獻。


查看完整回答
反對 回復 2021-10-31
  • 2 回答
  • 0 關注
  • 582 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號