ASP.NET Core添加異常處理

添加自定義Exception類

using System;
using System.Net;

namespace Application.Errors
{
    public class RestException:Exception
    {
        public RestException(HttpStatusCode code,object errors=null)
        {
            Code = code;
            Errors = errors;
        }

        public HttpStatusCode Code { get; }
        public object Errors { get; }
    }
}

添加中間件

中間件接受一個委托霎终,并且傳遞下一個委托給下一個中間件
創(chuàng)建中間件處理異常

using System;
using System.Net;
using System.Threading.Tasks;
using Application.Errors;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace API.Middleware
{
    public class ErrorHandlingMiddleware
    {
        private readonly ILogger<ErrorHandlingMiddleware> _logger;
        private readonly RequestDelegate _next;

        public ErrorHandlingMiddleware(RequestDelegate next,ILogger<ErrorHandlingMiddleware> logger)
        {
            _logger = logger;
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch(Exception ex)
            {
                await HandleExceptionAsync(context, ex, _logger);
            }
        }

        private async Task HandleExceptionAsync(HttpContext context, Exception ex, ILogger<ErrorHandlingMiddleware> logger)
        {
            object errors = null;

            switch(ex)
            {
                case RestException re:
                    logger.LogError(ex, "Rest Error");
                    errors = re.Errors;
                    context.Response.StatusCode = (int)re.Code;
                    break;
                case Exception e:
                    logger.LogError(ex, "Server Error");
                    errors = string.IsNullOrWhiteSpace(e.Message) ? "Error" : e.Message;
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    break;
            }

            context.Response.ContentType = "application/json";
            if(errors!=null)
            {
                var result = JsonConvert.SerializeObject(new
                {
                    errors
                });

                await context.Response.WriteAsync(result);
            }
        }
    }
}

在Startup類中使用中間件

app.UseMiddleware<ErrorHandlingMiddleware>();

請求響應(yīng)管道中的每一個委托都在前一個委托后執(zhí)行吠撮,所以應(yīng)當(dāng)盡量早的調(diào)用異常處理的委托

在Delete動作中拋出RestException

if (activity == null)
    throw new RestException(HttpStatusCode.NotFound, new { Activity = "Not Found" });

使用postMan測試



可以得到404的返回結(jié)果和返回的json對象

客戶端異常處理


使用ReactRouter
作路由導(dǎo)航
在 /layout/ 中添加NotFound.tsx組件作為404頁面

import React from 'react';
import { Segment, Button, Header, Icon } from 'semantic-ui-react';
import { Link } from 'react-router-dom';

const NotFound = () => {
    return (
        <Segment placeholder>
            <Header icon>
                <Icon name='search' />
                Oops - we've looked everywhere but couldn't find this.
            </Header>
            <Segment.Inline>
                <Button as={Link} to='/activities' primary>
                    Return to Activities page
                </Button>
            </Segment.Inline>
        </Segment>
    );
};

export default NotFound;

使用axios來捕獲服務(wù)端的異常

axios.interceptors.response.use(undefined, error=> {
  const { status, data, config } = error.response;
  if (status === 404) {
    history.push('/notfound')
  }
});
```>
這里的**history** 通過 Router組件進(jìn)行注入

export const history = createBrowserHistory();

ReactDOM.render(
<Router history={history}>
<ScrollToTop>
<App />
</ScrollToTop>
</Router>
, document.getElementById('root'));

接下來添加處理其他類型異常的邏輯
添加react-toastify
npm install react-toastify
[使用文檔](https://www.npmjs.com/package/react-toastify#usage)
在index頁面添加CSS朵耕,在App頁面中添加ToastContainer

<ToastContainer position='bottom-right' />

添加其他錯誤的處理邏輯

if (error.message === "Network Error" && !error.response) {
toast.error("NetWork Error");
}
const { status,data,config } = error.response;
if (status === 404) {
history.push('/notfound')
}
if (status === 400 && config.method === 'get' && data.errors.hasOwnProperty('id')) {
history.push('/notfound')
}
if (status === 500) {
toast.error('Server error,check your terminal!')
}





?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末疟羹,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子屹耐,更是在濱河造成了極大的恐慌期奔,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,039評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件仿畸,死亡現(xiàn)場離奇詭異食棕,居然都是意外死亡朗和,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評論 3 395
  • 文/潘曉璐 我一進(jìn)店門簿晓,熙熙樓的掌柜王于貴愁眉苦臉地迎上來眶拉,“玉大人,你說我怎么就攤上這事憔儿∫渲玻” “怎么了?”我有些...
    開封第一講書人閱讀 165,417評論 0 356
  • 文/不壞的土叔 我叫張陵谒臼,是天一觀的道長朝刊。 經(jīng)常有香客問我,道長蜈缤,這世上最難降的妖魔是什么拾氓? 我笑而不...
    開封第一講書人閱讀 58,868評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮底哥,結(jié)果婚禮上咙鞍,老公的妹妹穿的比我還像新娘。我一直安慰自己趾徽,他們只是感情好续滋,可當(dāng)我...
    茶點故事閱讀 67,892評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著附较,像睡著了一般吃粒。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上拒课,一...
    開封第一講書人閱讀 51,692評論 1 305
  • 那天徐勃,我揣著相機(jī)與錄音,去河邊找鬼早像。 笑死僻肖,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的卢鹦。 我是一名探鬼主播臀脏,決...
    沈念sama閱讀 40,416評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼冀自!你這毒婦竟也來了揉稚?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,326評論 0 276
  • 序言:老撾萬榮一對情侶失蹤熬粗,失蹤者是張志新(化名)和其女友劉穎搀玖,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體驻呐,經(jīng)...
    沈念sama閱讀 45,782評論 1 316
  • 正文 獨居荒郊野嶺守林人離奇死亡灌诅,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,957評論 3 337
  • 正文 我和宋清朗相戀三年芳来,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片猜拾。...
    茶點故事閱讀 40,102評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡即舌,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出挎袜,到底是詐尸還是另有隱情顽聂,我是刑警寧澤,帶...
    沈念sama閱讀 35,790評論 5 346
  • 正文 年R本政府宣布盯仪,位于F島的核電站芜飘,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏磨总。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,442評論 3 331
  • 文/蒙蒙 一笼沥、第九天 我趴在偏房一處隱蔽的房頂上張望蚪燕。 院中可真熱鬧,春花似錦奔浅、人聲如沸馆纳。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽鲁驶。三九已至,卻和暖如春舞骆,著一層夾襖步出監(jiān)牢的瞬間钥弯,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評論 1 272
  • 我被黑心中介騙來泰國打工督禽, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留脆霎,地道東北人。 一個月前我還...
    沈念sama閱讀 48,332評論 3 373
  • 正文 我出身青樓狈惫,卻偏偏與公主長得像睛蛛,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子胧谈,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,044評論 2 355

推薦閱讀更多精彩內(nèi)容