6

ServiceStack RESTサービスがあり、カスタムエラー処理を実装する必要があります。AppHostBase.ServiceExceptionHandlerをカスタム関数に設定することで、サービスエラーをカスタマイズできました。

ただし、検証エラーなどの他のタイプのエラーの場合、これは機能しません。どうすればすべてのケースをカバーできますか?

言い換えれば、私は2つのことを達成しようとしています。

  1. 非サービスエラー(検証)を含む、ポップアップする可能性のあるあらゆる種類の例外に対して、独自のHTTPステータスコードを設定します
  2. すべてのエラータイプについて、独自のカスタムエラーオブジェクト(デフォルトのResponseStatusではない)を返します

これを達成するにはどうすればよいですか?

4

2 に答える 2

11

AppHostBase.ServiceExceptionHandlerグローバルハンドラーは、サービス例外のみを処理しますAppHostBase.ExceptionHandlerサービスの外部で発生する例外を処理するには、グローバルハンドラーを設定できます。例:

public override void Configure(Container container)
{
    //Handle Exceptions occurring in Services:
    this.ServiceExceptionHandler = (request, exception) => {

        //log your exceptions here
        ...

        //call default exception handler or prepare your own custom response
        return DtoUtils.HandleException(this, request, exception);
    };

    //Handle Unhandled Exceptions occurring outside of Services, 
    //E.g. in Request binding or filters:
    this.ExceptionHandler = (req, res, operationName, ex) => {
         res.Write("Error: {0}: {1}".Fmt(ex.GetType().Name, ex.Message));
         res.EndServiceStackRequest(skipHeaders: true);
    };
}

非サービス でDTOを作成して応答ストリームにシリアル化するには、IAppHost.ContentTypeFiltersからの要求に対して正しいシリアライザーExceptionHandlerにアクセスして使用する必要があります。

詳細については、エラー処理wikiページを参照してください。

于 2013-03-24T22:08:10.123 に答える
4

@mythzの回答を改善しました。

public override void Configure(Container container) {
    //Handle Exceptions occurring in Services:

    this.ServiceExceptionHandlers.Add((httpReq, request, exception) = > {
        //log your exceptions here
        ...
        //call default exception handler or prepare your own custom response
        return DtoUtils.CreateErrorResponse(request, exception);
    });

    //Handle Unhandled Exceptions occurring outside of Services
    //E.g. Exceptions during Request binding or in filters:
    this.UncaughtExceptionHandlers.Add((req, res, operationName, ex) = > {
        res.Write("Error: {0}: {1}".Fmt(ex.GetType().Name, ex.Message));

#if !DEBUG
        var message = "An unexpected error occurred."; // Because we don't want to expose our internal information to the outside world.
#else
        var message = ex.Message;
#endif

        res.WriteErrorToResponse(req, req.ContentType, operationName, message, ex, ex.ToStatusCode()); // Because we don't want to return a 200 status code on an unhandled exception.
    });
}
于 2015-09-04T19:34:54.797 に答える