diff --git a/Src/Witsml/EndpointBehaviour.cs b/Src/Witsml/EndpointBehaviour.cs index 8e53b60c7..5196df138 100644 --- a/Src/Witsml/EndpointBehaviour.cs +++ b/Src/Witsml/EndpointBehaviour.cs @@ -1,8 +1,10 @@ using System; +using System.Net; using System.Net.Http; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; +using System.ServiceModel.Security; using System.Threading; using System.Threading.Tasks; @@ -28,10 +30,20 @@ public CustomDelegatingHandler(HttpMessageHandler handler) InnerHandler = handler; } - protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { request.Headers.Add("user-agent", "witsml-explorer"); - return base.SendAsync(request, cancellationToken); + var response = await base.SendAsync(request, cancellationToken); + + switch (response.StatusCode) + { + case HttpStatusCode.InternalServerError: + throw new WitsmlRemoteServerRequestCrashedException("WITSML remote request failed on the server."); + case HttpStatusCode.Unauthorized: + case HttpStatusCode.Forbidden: + throw new MessageSecurityException("Not able to authenticate to WITSML server with given credentials"); + } + return response; } } } diff --git a/Src/Witsml/WitsmlRemoteServerRequestCrashedException.cs b/Src/Witsml/WitsmlRemoteServerRequestCrashedException.cs new file mode 100644 index 000000000..ffa1bdc21 --- /dev/null +++ b/Src/Witsml/WitsmlRemoteServerRequestCrashedException.cs @@ -0,0 +1,11 @@ +using System.ServiceModel; + +namespace Witsml; + +/// +/// This class represents a custom exception for cases where a WITSML remote server request crash. +/// +public class WitsmlRemoteServerRequestCrashedException : CommunicationException +{ + public WitsmlRemoteServerRequestCrashedException(string message) : base(message) { } +} diff --git a/Src/WitsmlExplorer.Api/Middleware/ExceptionMiddleware.cs b/Src/WitsmlExplorer.Api/Middleware/ExceptionMiddleware.cs index 0620210da..6c9b9e27a 100644 --- a/Src/WitsmlExplorer.Api/Middleware/ExceptionMiddleware.cs +++ b/Src/WitsmlExplorer.Api/Middleware/ExceptionMiddleware.cs @@ -8,6 +8,8 @@ using Serilog; +using Witsml; + using WitsmlExplorer.Api.Configuration; using WitsmlExplorer.Api.Extensions; using WitsmlExplorer.Api.HttpHandlers; @@ -51,6 +53,16 @@ public async Task InvokeAsync(HttpContext httpContext) }; await HandleExceptionAsync(httpContext, errorDetails); } + catch (WitsmlRemoteServerRequestCrashedException ex) + { + Log.Error($"Invalid response from server: {ex}"); + ErrorDetails errorDetails = new() + { + StatusCode = (int)HttpStatusCode.InternalServerError, + Message = "WITSML remote request failed on the server." + }; + await HandleExceptionAsync(httpContext, errorDetails); + } catch (MessageSecurityException ex) { Log.Debug($"Not valid credentials: {ex}");