public (ProblemDetails error, HttpStatusCode statusCode)? Handle(Exception exception, HttpContext httpContext) { if (!(exception is EntityNotFoundException)) { return(null); } var entityType = exception.GetEntityType(); var problemDetails = new ProblemDetails { Type = entityType.Name }; foreach (var(key, value) in exception.GetErrorDetailFields()) { problemDetails.Extensions.Add(key, value); } return(problemDetails, HttpStatusCode.NotFound); }
public async Task <IActionResult> GetAllInstitutions() { IEnumerable <Institution> institutions = await institutionService.GetInstitutionsAsync(); if (!institutions.Any()) { ProblemDetails problem = new ProblemDetails { Title = "No Institutions found", Detail = "There where no institutions scopes found.", Instance = "7736D583-3263-4946-BF48-35299812AA56" }; return(NotFound(problem)); } IEnumerable <InstitutionResourceResult> model = mapper.Map <IEnumerable <Institution>, IEnumerable <InstitutionResourceResult> >(institutions); return(Ok(model)); }
public async Task Invoke(HttpContext context) { var problemDetails = new ProblemDetails { Instance = $"urn:elearningapp:{Guid.NewGuid()}" }; try { await _next(context); } catch (Exception exception) { problemDetails.Status = StatusCodes.Status500InternalServerError; problemDetails.Detail = exception.Message; problemDetails.Title = Constants.InternalServerError; context.Response.StatusCode = StatusCodes.Status500InternalServerError; context.Response.WriteJson(problemDetails); } }
public async Task <IActionResult> DeleteAccount() { User user = await HttpContext.GetContextUser(userService).ConfigureAwait(false); if (await userService.FindAsync(user.Id) == null) { ProblemDetails problem = new ProblemDetails { Title = "Failed getting the user account.", Detail = "The database does not contain a user with this user id.", Instance = "C4C62149-FF9A-4E4C-8C9F-6BBF518BA085" }; return(NotFound(problem)); } await userService.RemoveAsync(user.Id); userService.Save(); return(Ok()); }
public async Task <IActionResult> DeleteInstitution(int institutionId) { Institution institution = await institutionService.FindAsync(institutionId); if (institution == null) { ProblemDetails problem = new ProblemDetails { Title = "Failed getting the institution.", Detail = "The database does not contain an institution with that id.", Instance = "9981200A-B22C-42B3-8035-5D3A6B9696C8" }; return(NotFound(problem)); } await institutionService.RemoveAsync(institutionId); institutionService.Save(); return(Ok()); }
private static Task HandleExceptionAsync(HttpContext context, Exception ex) { var code = HttpStatusCode.InternalServerError; var problem = new ProblemDetails { Type = "https://www.etf.edu.ba/server-error", Title = "Internal Server Error", Detail = ex.Message, Instance = "", Status = (int)code }; var result = JsonSerializer.ToString(problem); context.Response.ContentType = "application/problem+json"; context.Response.StatusCode = (int)code; return(context.Response.WriteAsync(result)); }
public IActionResult Error() { var feature = HttpContext.Features.Get <IExceptionHandlerPathFeature>(); var ex = feature?.Error; string CorrelationId = Guid.NewGuid().ToString(); string ErrorMessage = $"Something went wrong. Use this correlation id to investigate problem. CorrelationId: {CorrelationId}"; logger.LogError(ex, ErrorMessage); var problemDetails = new ProblemDetails { Status = (int)HttpStatusCode.InternalServerError, Instance = feature?.Path, Title = ErrorMessage, Detail = null }; return(StatusCode(problemDetails.Status.Value, problemDetails)); }
private static async Task WriteProblemDetailsResponse <T>(HttpContext context, T ex) where T : UserValidationException { Console.WriteLine($"Error: {ex.Message}. {ex.FieldName}." + $"{ ex.ProblemFieldValue} has been entered"); ProblemDetails problem = new ProblemDetails() { Type = "ttps://httpstatuses.com/500", Title = ex.Message, Status = 500, Detail = $"Error: {ex.Message}. {ex.FieldName}." + $" {ex.ProblemFieldValue} has been entered", Instance = context.Request.Path }; problem.Extensions.Add(nameof(T), ex.ToString()); context.Response.StatusCode = (int)StatusCodes.Status500InternalServerError; await context.Response.WriteAsJsonAsync(problem); }
public IActionResult Error([FromServices] IHostingEnvironment webHostingEnvironment) { var feature = HttpContext.Features.Get <IExceptionHandlerPathFeature>(); Exception ex = feature?.Error; bool isDev = webHostingEnvironment.IsDevelopment(); if (ex == null) { return(StatusCode(500)); } var problemDetails = new ProblemDetails { Status = (int)HttpStatusCode.InternalServerError, Instance = feature?.Path, Title = isDev ? $"{ex.GetType().Name}: {ex.Message}" : "An error occurred.", Detail = isDev ? ex.StackTrace : null, }; return(StatusCode(problemDetails.Status.Value, problemDetails)); }
public override void OnException(ExceptionContext context) { if (context.Exception is SqlException || context.Exception?.InnerException is SqlException) { string exceptionMessage = context.Exception.CompleteExceptionMessage(); logger.LogDebug("SQL Exception {0}", exceptionMessage); context.ExceptionHandled = true; var problemDetails = new ProblemDetails { Detail = exceptionMessage, Title = "SqlException", Instance = context.HttpContext.TraceIdentifier }; context.Result = new ObjectResult(problemDetails) { ContentTypes = { "application/problem+json" }, StatusCode = StatusCodes.Status500InternalServerError }; } }
public async Task <IActionResult> GetUserTasksForCurrentUser() { User currentUser = await HttpContext.GetContextUser(userService) .ConfigureAwait(false); if (currentUser == null) { ProblemDetails problem = new ProblemDetails { Title = "Failed getting the user account.", Detail = "The user could not be found in the database.", Instance = "548DA96F-0183-483F-8CE9-2848A868DC57" }; return(NotFound(problem)); } List <UserTask> userTasks = await userTaskService.GetUserTasksForUser(currentUser.Id); return(Ok(userTasks)); }
public override void OnActionExecuting(ActionExecutingContext context) { var modelState = context.ModelState; if (!modelState.IsValid) { ProblemDetails error = new ProblemDetails { Title = "Invalid Data", Status = (int)System.Net.HttpStatusCode.BadRequest }; List <string> errorDetails = modelState.Keys .SelectMany(key => modelState[key].Errors.Select(x => $"{key}: { (string.IsNullOrEmpty(x.ErrorMessage) ? x.Exception.Message : x.ErrorMessage) }")) .ToList(); error.Detail = string.Join("\n", errorDetails.ToArray()); context.Result = new BadRequestObjectResult(error); } }
/// <summary> /// Creates and returns a representation of the HTTP response error as a ProblemDetailsResult. /// </summary> /// <param name="response">The HTTP response.</param> /// <returns>A representation of the response error as a ProblemDetailsResult.</returns> public IStatusCodeActionResult Map(HttpResponse response) { _ = response ?? throw new ArgumentNullException(nameof(response)); if (!CanMap(response.StatusCode)) { throw new ArgumentOutOfRangeException(nameof(response), response, $"HttpResponse status is not {Status}."); } var problemDetails = new ProblemDetails { Status = MapStatus(response), Type = MapType(response), Title = MapTitle(response), Detail = MapDetail(response), Instance = MapInstance(response) }; return(new ProblemDetailsResult(problemDetails)); }
public void SetProblemDetails(ProblemDetails problemDetails, int statusCode) { problemDetails.Instance = this._requestPath; problemDetails.Status = statusCode; var traceId = Activity.Current?.Id ?? _traceId; problemDetails.Extensions[TRACE_IDENTIFIER_KEY] = traceId; if (ClientErrorMapping.TryGetValue(statusCode, out var errorData)) { problemDetails.Title = errorData.Title; problemDetails.Type = errorData.Link; } else { problemDetails.Type = string.Format(STATUS_CODE_TYPE_URI, statusCode); problemDetails.Title = ReasonPhrases.GetReasonPhrase(statusCode); } }
private void HandleGenericException(ExceptionContext context, Exception exception) { var statusCode = (int)HttpStatusCode.InternalServerError; var includeDebuggingInformation = _environmentType.IsLocal(); var details = includeDebuggingInformation ? exception.ToString() : null; var title = includeDebuggingInformation ? exception.Message : "An unhandled ajax exception was thrown"; var problemDetails = new ProblemDetails { Status = statusCode, Type = $"https://httpstatuses.com/{statusCode.ToString()}", Title = title, Detail = details }; _logger.Error(exception, "An unhandled ajax exception was thrown: {ErrorMessage}.", exception.Message); context.HttpContext.Response.StatusCode = statusCode; context.Result = new JsonResult(problemDetails); }
public ActionResult <IScanJobStatus> GetJobStatusById(string deviceId, string jobId) { try { IScanJobStatus jobStatus = scanJobService.GetJobStatusById(deviceId, jobId); return(new OkObjectResult(jobStatus)); } catch (Exception) { ProblemDetails problemDetails = new ProblemDetails() { Title = "Scanner", Detail = "Unable to enumerate scanners", Status = StatusCodes.Status500InternalServerError, Instance = HttpContext.Request.Path }; return(StatusCode(StatusCodes.Status500InternalServerError, problemDetails)); } }
public async Task <T> GetResponseResult(HttpResponseMessage responseMessage) { T result = default; ResetErrors(); switch (responseMessage.StatusCode.ToString()) { case "200": result = await responseMessage.Content.ReadAsJsonAsync <T>(); break; case "500": ErrorOccured = true; ErrorDetails = await responseMessage.Content.ReadAsJsonAsync <ProblemDetails>(); break; } return(result); }
public async Task OpenGraphReturnsBadRequestWhenEmptyPayload() { // Arrange List <OpenGraphRequest> openGraphRequests = null; // Act ActionResult <OpenGraphResult> result = await _openGraphController.PostAsync(openGraphRequests); // Assert Assert.IsType <BadRequestObjectResult>(result.Result); BadRequestObjectResult badRequestResult = result.Result as BadRequestObjectResult; Assert.IsType <ProblemDetails>(badRequestResult.Value); ProblemDetails problemDetails = badRequestResult.Value as ProblemDetails; Assert.Equal("Could not validate links", problemDetails.Title); Assert.Equal(problemDetails.Status, StatusCodes.Status400BadRequest); }
public static ProblemDetails Generate(Microsoft.AspNetCore.Identity.SignInResult result) { var problemDetails = new ProblemDetails() { Type = "SignInError", Title = "One or more errors during sign-in." }; var reason = "InvalidSignIn"; if (result.RequiresTwoFactor) { reason = "TwoFactor"; } if (result.IsLockedOut) { reason = "LockedOut"; } if (result.IsNotAllowed) { reason = "CredentialUnconfirmed"; } problemDetails.AddExtension("reason", reason); if (reason == "InvalidSignIn") { problemDetails.AddErrors(new List <ErrorItem>() { new ErrorItem() { Key = "Credentials", Descriptions = new string[] { "Invalid email address or password." } } }); } return(problemDetails); }
public async Task <IActionResult> DeleteRole(int roleId) { Role role = await roleService.FindAsync(roleId).ConfigureAwait(false); if (role == null) { ProblemDetails problem = new ProblemDetails { Title = "Failed to delete the role.", Detail = "The role could not be found in the database.", Instance = "CBC4C09D-DFEA-44D8-A310-2CE149BAD498" }; return(NotFound(problem)); } if (role.Name == nameof(Defaults.Roles.Administrator) || role.Name == nameof(Defaults.Roles.RegisteredUser)) { ProblemDetails problem = new ProblemDetails { Title = "Not allowed.", Detail = "For the stability of the program we need at least the registered user role and the admin role so these are not deletable..", Instance = "CBC4C09D-DFEA-44D8-A310-2CE14123D498" }; return(Unauthorized(problem)); } if (userService.UserWithRoleExists(role)) { ProblemDetails problem = new ProblemDetails { Title = "Role is still assigned.", Detail = "The role is still assigned to a user.", Instance = "46E4AD0A-5947-4F9B-8001-A4D77CBC1A92" }; return(BadRequest(problem)); } await roleService.RemoveAsync(role.Id).ConfigureAwait(false); roleService.Save(); return(Ok()); }
public static void UseProblemDetailsExceptionHandler(this IApplicationBuilder app, ILoggerFactory loggerFactory) { app.UseExceptionHandler(builder => { builder.Run(async context => { var exceptionHandlerFeature = context.Features.Get <IExceptionHandlerFeature>(); if (exceptionHandlerFeature != null) { var exception = exceptionHandlerFeature.Error; var problemDetails = new ProblemDetails { Instance = context.Request.HttpContext.Request.Path }; if (exception is ValidationException validationException) { problemDetails.Title = "The request is invalid"; problemDetails.Status = StatusCodes.Status400BadRequest; problemDetails.Detail = validationException.Message; } else { var logger = loggerFactory.CreateLogger("GlobalExceptionHandler"); logger.LogError($"Unexpected error: {exceptionHandlerFeature.Error}"); problemDetails.Title = exception.Message; problemDetails.Status = StatusCodes.Status500InternalServerError; } context.Response.StatusCode = problemDetails.Status.Value; context.Response.ContentType = "application/problem+json"; var json = JsonConvert.SerializeObject(problemDetails, SerializerSettings.JsonSerializerSettings); await context.Response.WriteAsync(json); } }); }); }
public async Task <IActionResult> UploadSingleFile([FromForm] FileResource fileResource) { if (fileResource.File == null) { ProblemDetails problem = new ProblemDetails { Title = "Failed posting file.", Detail = "File is null.", Instance = "ACD46F17-A239-4353-92A5-0B81AA0A96E9" }; return(BadRequest(problem)); } try { DateTime uploadDateTime = DateTime.Now; int fileExtPos = fileResource.File.FileName.LastIndexOf("."); string extension = fileResource.File.FileName.Substring(fileExtPos); string newFileName = Guid.NewGuid() + extension; User user = await HttpContext.GetContextUser(userService) .ConfigureAwait(false); File file = new File(newFileName, newFileName, user, uploadDateTime); await fileUploader.CopyFileToDirectory(fileResource.File, newFileName); await fileService.AddAsync(file); fileService.Save(); return(Ok(mapper.Map <File, FileResourceResult>(file))); } catch (FileExistException fileExistException) { ProblemDetails problem = new ProblemDetails { Title = fileExistException.Message, Detail = "Please rename filename.", Instance = "D902F8C6-23FF-4506-B272-C757BD709464" }; return(BadRequest(problem)); } }
public (ProblemDetails error, HttpStatusCode statusCode)? Handle(Exception exception, HttpContext httpContext) { if (!(exception is DomainRuleException domainRuleException)) { return(null); } var type = domainRuleException.GetEntityType(); var problemDetails = new ProblemDetails { Title = type?.Name, Detail = domainRuleException.Message }; foreach (var(key, value) in exception.GetErrorDetailFields()) { problemDetails.Extensions.Add(key, value); } return(problemDetails, HttpStatusCode.UnprocessableEntity); }
public async Task InvokeAsync(HttpContext context) { var errorFeature = context.Features.Get <IExceptionHandlerFeature>(); var exception = errorFeature?.Error; var problemDetails = new ProblemDetails { Title = ErrorTypes.ApiError, Status = StatusCodes.Status500InternalServerError }; if (exception != null) { problemDetails.Detail = exception.GetFullMessage(); } context.Response.StatusCode = StatusCodes.Status500InternalServerError; context.Response.ContentType = MediaTypeNames.Application.ProblemDetails.Json; _logger.LogWarning("Internal Server Error {@Error}", problemDetails); await context.Response.WriteAsync(JsonConvert.SerializeObject(problemDetails)); }
public async Task <IActionResult> UploadToBlob([FromForm] UserPhotoRequest request) { var uploadToBlobResult = await _savedItemsService.UploadToBlob(request); if (uploadToBlobResult.Error == null) { return(Ok(uploadToBlobResult.Url)); } var problemDetals = new ProblemDetails { Status = 400, Title = uploadToBlobResult.Error }; return(new ObjectResult(problemDetals) { ContentTypes = { "application/problem+json" }, StatusCode = 400 }); }
public async Task <IActionResult> DeleteProject(long projectId) { var user = await _userManager.GetUserAsync(HttpContext.User); var project = await _projectsAppService.DeleteProjectAsync(user, projectId); if (project == null) { var problem = new ProblemDetails { Instance = HttpContext.Request.Path, Status = StatusCodes.Status404NotFound, Type = $"https://httpstatuses.com/404", Title = "Not found", Detail = $"Project {projectId} does not exist or you do not have access to it." }; return(NotFound(problem)); } return(Ok(project)); }
public async Task <IActionResult> DeleteCollaborator(long projectId, string name) { var user = await _userManager.GetUserAsync(HttpContext.User); var collaborator = await _projectsAppService.DeleteCollaboratorAsync(user, projectId, name); if (collaborator == null) { var problem = new ProblemDetails { Instance = HttpContext.Request.Path, Status = StatusCodes.Status404NotFound, Type = $"https://httpstatuses.com/404", Title = "Not found", Detail = $"Collaborator {name} does not collaborate in this project." }; return(NotFound(problem)); } return(Ok(collaborator)); }
public async Task <IActionResult> DeleteCallToActionOption(int id) { CallToActionOption option = await callToActionOptionService.FindAsync(id); if (option == null) { ProblemDetails problem = new ProblemDetails { Title = "Failed getting the call to action option.", Detail = "The database does not contain a call to action option with that id.", Instance = "6BDD3202-AE32-4CC1-AA87-42A2870CE8E6" }; return(NotFound(problem)); } await callToActionOptionService.RemoveAsync(id); callToActionOptionService.Save(); return(Ok()); }
/// <summary> /// Writes the specified problem details object to the HTTP response stream. /// </summary> /// <param name="problemDetails"> /// The problem details. /// </param> /// <param name="response"> /// The HTTP response. /// </param> /// <param name="stream"> /// The destination response stream. /// </param> /// <returns> /// A <see cref="Task"/> that will perform the write. /// </returns> private async Task WriteProblemDetailsToStream(ProblemDetails problemDetails, IOwinResponse response, Stream stream) { // Create a new buffer, and then create and serialize a problem details object // into the new buffer. using (var ms = new MemoryStream()) { var content = new ObjectContent( problemDetails.GetType(), problemDetails, new JsonMediaTypeFormatter(), ClientErrorDataDefaults.MediaType ); await content.CopyToAsync(ms).ConfigureAwait(false); // Now set the content type and content length on the response, and copy // the content of the new buffer into the original response stream. response.ContentType = content.Headers.ContentType.ToString(); response.ContentLength = ms.Length; ms.Position = 0; await ms.CopyToAsync(stream).ConfigureAwait(false); } }
public static async Task <string> OnGetRelay(string vURL) { await Task.Run(() => { }); try { HttpClient client = new HttpClient(); var msg = client.GetStringAsync(vURL).Result; return(msg); } catch (Exception ex) { ProblemDetails res = new ProblemDetails { Status = 500, Title = ex.Message }; return(res.ToString()); } }