Why does the HttpErrorResponse consistently show "OK" in the statusText field?

Constantly Receiving StatusText: "OK"

I recently configured HTTPS SSL certification for testing purposes, but I keep getting the "OK" status in StatusText. Ideally, it should return "Bad Request" or "Unauthorized"...etc. I would appreciate some assistance in understanding whether the error is in the startup class or in the Angular front-end.

view image description here

API Controller Issue

[ApiController]
[Route("api/[controller]")]
public class BuggyController : BaseApiController
{
    private readonly ApplicationContext __context;
    public BuggyController(ApplicationContext _context)
    {
        __context = _context;

    }
    [Authorize]
    [HttpGet("auth")]
    public ActionResult<string> GetSecret()
    {
        return Ok("secret Text");
    }

    [HttpGet("not-found")]
    public ActionResult<AppUser> GetNotFound()
    {
        var userIsExsists = __context.AppUsers.Find(-1);

        if (userIsExsists == null) return NotFound();

        return Ok(userIsExsists);
    }

    [HttpGet("server-error")]
    public ActionResult<string> GetServerError()
    {
        var userIsExsists = __context.AppUsers.Find(-1);

        var response = userIsExsists.ToString();

        return response;
    }

    [HttpGet("bad-request")]
    public ActionResult<string> GetBadRequest()
    {
        return BadRequest("This Request Is a Bad Request!");
    }
}

.NET Custom Exception Middleware Class

 public class ExceptionMiddleware
    {
        private readonly RequestDelegate next;
        private readonly ILogger<ExceptionMiddleware> logger;
        private readonly IHostEnvironment env;

        public ExceptionMiddleware(
            RequestDelegate next,
            ILogger<ExceptionMiddleware> logger,
            IHostEnvironment env)
        {
            this.next = next;
            this.logger = logger;
            this.env = env;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                context.Response.ContentType = "Application/Json";
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                var response = env.IsDevelopment()
                ? new ApiException(context.Response.StatusCode, ex.Message, ex.StackTrace.ToString(),
                Guid.NewGuid().ToString()) : new ApiException(context.Response.StatusCode, "Something Happend Wrong!");

                var jsonOption = new JsonSerializerOptions{PropertyNamingPolicy = JsonNamingPolicy.CamelCase};

                var jsonResponse = JsonSerializer.Serialize(response, jsonOption);

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

Utilization Of Custom Middleware

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseMiddleware<ExceptionMiddleware>();

            app.UseHttpsRedirection();
            
            if (env.IsDevelopment())
            {
                //app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));
            }

            app.UseRouting();

            app.UseCors(policy =>
            policy.AllowAnyHeader()
            .AllowAnyMethod()
            .WithOrigins("https://localhost:4200"));

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

Angular Interceptor Class

@Injectable()
export class ErrorsInterceptor implements HttpInterceptor {
  constructor(private route: Router, private toast: ToastrService) {}

  intercept(
    request: HttpRequest<unknown>,
    next: HttpHandler
  ): Observable<HttpEvent<unknown>> {
    return next.handle(request).pipe(
      catchError((errorResponse) => {
        if (errorResponse) {
          switch (errorResponse.status) {
            case 400:
              if (errorResponse.error.errors) {
                const modelStateErrors = [];
                for (const key in errorResponse.error.errors) {
                  if (errorResponse.error.errors[key]) {
                    modelStateErrors.push(errorResponse.error.errors[key]);
                  }
                }
                throw modelStateErrors;
              } else {
                this.toast.error(errorResponse.statusText, errorResponse.status);
              }
              break;
            case 401:
              this.toast.error(errorResponse.statusText, errorResponse.status);
              break;
            case 404:
              this.route.navigateByUrl("/not-found");
              break;
            case 500:
              const navigationExtras: NavigationExtras = {
                state: { error: errorResponse.error },
              };
              this.route.navigateByUrl("/server-error", navigationExtras);
              break;
            default:
              this.toast.error("Something Unexpected Happened!");
              console.log(errorResponse);
          }
        }
        return throwError(errorResponse);
      })
    );
  }
}

Calling API Endpoints

    get404Error() {
    this.http.get(this.baseUrl + "buggy/not-found").subscribe(
      (response) => {
        console.log(response);
      },
      (error) => {
        console.log(error);
      }
    );
  }
  get400Error() {
    this.http.get(this.baseUrl + "buggy/bad-request").subscribe(
      (response) => {
        console.log(response);
      },
      (error) => {
        console.log(error);
      }
    );
  }
  get500Error() {
    this.http.get(this.baseUrl + "buggy/server-error").subscribe(
      (response) => {
        console.log(response);
      },
      (error) => {
        console.log(error);
      }
    );
  }
  get401Error() {
    this.http.get(this.baseUrl + "buggy/auth").subscribe(
      (response) => {
        console.log(response);
      },
      (error) => {
        console.log(error);
      }
    );
  }
  get400ValidationError() {
    this.http.post(this.baseUrl + "Acccount/Register", { }).subscribe(
      (response) => {
        console.log(response);
      },
      (error) => {
        console.log(error);
      }
    );
  }

Answer №1

The problem was discovered when I implemented a local domain with a free SSL certificate for testing purposes. This forced the use of HTTPS instead of HTTP, causing the issue to arise. Switching back to HTTP resolved the problem.

view an image related to this issue here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combining data types in TypeScript (incorporating new keys into an existing keyof type)

If I have a typescript type with keys: const anObject = {value1: '1', value2: '2', value3: '3'} type objectKeys = keyof typeof anObject and I want to add additional keys to the type without manually defining them, how can I ...

Creating a variable within an ngFor loop

For my angular2 project, I need to display a matrix of workers and courses. Here's the current code I am using: <tr *ngFor="let worker of workers"> <td class="{{worker.fired ? 'fired-worker':''}}">{{worker.lastName ...

The ngx-toaster message is showing a delay of about 30-40 seconds before displaying on the browser in Angular 11

Within the App.module file: Include ToastrModule in appModule ToastrModule.forRoot({ timeOut: 3000, preventDuplicates: true, }), Inside a specific component: this.toastr.error("test err"); The error message is taking quite a while to disp ...

The problem with .NET regex is that it does not properly match digits between optional text when using possessive quant

I am grappling with this regex puzzle: Regex myRegex = new Regex(@"^[a-zA-Z .:_-]+([0-9]+)[a-zA-Z .:_-]*+$"); My goal is to extract a digit code in a specific way: "Order No. 0123456 lorem ipsum" - MATCH 0123456 in Group 1 "No. 0123456" - MATCH 0123456 ...

How can I access the most up-to-date state value in an event listener within a React element?

Here is the code I am working with: var C = () => { var [s, setS] = useState(0) var dRef = useRef<HTMLDivElement>() useMount(() => { setShortcut("ArrowDown", () => { setS(s+1) }) }) return ...

Establishing parameters in C# to prevent dates in database columns from matching any selections made in an HTML form

In my Asp.Net MVC project, the database is successfully connected and data is being stored in Microsoft SQL Server based on an ID. However, I am facing an issue with two date columns named "pickupDate" & "dropoffDate" in my Database table. The data saved i ...

How can I display data both as a dropdown and an autocomplete in Angular using a textbox?

There is a textbox with autocomplete functionality. When the user clicks on the textbox, an API call is made with two parameters - Pubid and Date. The data is then displayed in a dropdown with autocomplete feature. Now I am attempting to have the data app ...

Unique Constraint in EF Core for Two Separate Entities

Imagine having 2 separate entities with no relationship between them. To ensure unique addresses in the database, one can implement the following approach: public class SaleAddress : SaveConfig { [Key] [Required] ...

What is the correct way to handle errors in TypeScript when using Axios?

I've got this code snippet that's currently working: try { self.loadingFrameMarkup = true; const { data }: AxiosResponse<IMarkupFrameData> = yield axios.post<IMarkupFrameData>( ...

Decoding JSON data in C#

When working with a WebService, I often deserialize objects using the following method: var content = JsonConvert.DeserializeObject<Member>(result); Below is the sample JSON data: { "CREATE": [ { "isValidMemberPassword": true, "m ...

Maintaining component state during route changes in Angular routing

After successfully incorporating lazy loading into my Angular application, I noticed that when I switch pages, the previously loaded page reverts back to its initial state (ngOnInit being triggered again). { path: '/posts', loadChildren: () => ...

Can ExecuteUpdate be configured to follow session filters?

I've been experimenting with the ExecuteUpdate method in the query below, but I'm having trouble getting it to respect session filters. Is there a way to accomplish this? //Even after enabling the filter, it doesn't seem to have any effect. ...

Why is my Angular 2 service not showing up in my application?

Trying to access a JSON file using an Angular service has been unsuccessful. While I can easily read and bind the JSON data without the service, attempting to do so with the service results in an error message: Failed to load resource: the server responde ...

Why is it that Eslint Plugins are present locally, but I am unable to compile them on the server?

The ESlint command is encountering an error on the server during the build process: ESLint couldn't find the plugin "@typescript-eslint/eslint-plugin". However, everything is running smoothly on the local environment. Since there is no global eslint ...

Having trouble with Angular2 testing? It seems like you may be missing the 'angularCli.config' entry in your Karma configuration

When I attempt to run 'npm test' in my Angular2 project, I encounter the following error: "Missing 'angularCli.config' entry in Karma config" Does anyone have any insights on how to resolve this? ...

Pass on only the necessary attributes to the component

I have a simple component that I want to include most, if not all, of the default HTML element props. My idea was to possibly extend React.HTMLAttributes<HTMLElement> and then spread them in the component's attributes. However, the props' ...

Having trouble getting material-ui container to work with custom breakpoints in TypeScript?

Currently, I am exploring material-ui and typescript within my educational project. However, I have encountered a perplexing issue for which I am seeking assistance. In this project, I utilize custom breakpoints in the material-ui theme settings. import { ...

Is there a way to resolve the warning message "The shadow-piercing descendant combinator (>>>) is deprecated" that appears when running ng build for production?

I keep receiving warnings when I run ng-build -c production for all my styles that contain the '>>>' notation. Warning: ▲ [WARNING] Unexpected ">" /Users/mike/project2022/client/src/app/bank/bank-new/bank-new.component.ts-angular- ...

Retrieve information from the app-root and transfer it to the component

<body> <app-root data="myData"></app-root> </body> I have added the myData at index.html and now I want to retrieve it to use in a component. What is the best way to access this data? Thank you. ...

Unique login system for an ASP.NET site

I'm in the process of developing an ASP.NET website and I'm looking to implement a custom, yet simple login system. I decided to begin with the well-known Employee Info Starter Kit Here is what I have accomplished so far: On an ASP.NET page: p ...