Manage all HTTP error responses consistently

Whenever a call is made to my API, it goes through a service I have created using methods such as "GET, POST, PUT, DELETE, PATCH". In case any of these calls fail, I want to display the error in an alert and if the error status is 401, redirect the user to the login page. How can I create a generic error handler for this?

api.service.ts

import { Injectable } from '@angular/core';
import { Http, RequestOptions, RequestOptionsArgs, Response, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import lodash from 'lodash';

@Injectable()
export class ApiService {

  url: string = 'https://leetags-api.herokuapp.com';
  options: RequestOptions = new RequestOptions({
    withCredentials: true
  });

  constructor(private http: Http) {}

  get(endpoint: string, params?: any, options: RequestOptionsArgs = {}): Observable<Response> {
    if (params) {
      const urlSearchParams: URLSearchParams = new URLSearchParams();
      lodash.forEach(params, (value: any, key: string): void => urlSearchParams.set(key, value));
      options.search = !options.search ? urlSearchParams : options.search;
    }

    return this.http.get(`${this.url}/${endpoint}`, this.options.merge(options));
  }

  post(endpoint: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.post(`${this.url}/${endpoint}`, body, this.options.merge(options));
  }

  put(endpoint: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.put(`${this.url}/${endpoint}`, body, this.options.merge(options));
  }

  delete(endpoint: string, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.delete(`${this.url}/${endpoint}`, this.options.merge(options));
  }

  patch(endpoint: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.put(`${this.url}/${endpoint}`, body, this.options.merge(options));
  }

}

Answer №1

To enhance error handling in your service, you can implement a custom catch() method and link it to the catch handler of your http call. This .catch block will be triggered automatically whenever an API call fails.

Modify your existing http statement as shown below (for GET):

get() {
        return this._http.get(this.getUserUrl)
                .map((response: Response) => response.json())
                .catch(this.myCatchFunction);
    }

myCatchFunction(error: Response){
 //Include specific error codes handling logic here
}

I hope this solution proves helpful!

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

Using NodeJS and ExpressJS to send the HTTP request response back to the client

After creating a website using Angular 2 and setting up node.js as the backend, I successfully established communication between the Angular client and the node.js server. From there, I managed to forward requests to another application via HTTP. My curren ...

What is the process of modifying the data in DataTables once it has already been initialized?

I am looking to dynamically populate a table using datatables through an ajax request. Here is the approach I have taken: $(function(e) { $('#CampaignMenu').change(function(e) { $('#ReportWrapper').hide(); ...

What is the reason for the value of an object's key becoming undefined when it is set within a loop?

I've always wondered why setting a certain object's key as its own value in a loop results in undefined. Take this code block, for example: var text = 'this is my example text', obj = {}, words = text.split(' '); for (i = ...

Incorporating an Array into a JSON Object and transmitting it to a server

I have stored an Object in a .json file that contains only an Array. Now I want to prompt the user for a word and add it to this Array. Below are the relevant code snippets: function addWord() { let myWords = getWords(); let newWord = prompt("Ple ...

How to Implement an Asynchronous Function in Node.js

I'm currently trying to grasp the concept of async/await in NodeJS. Within a file, I have a function structured like this: const getAccessToken = async () => { return new Promise((resolve, reject) => { const oauthOptions = { metho ...

Assess JavaScript for Fetch API implementation

Currently, I am utilizing node.js on Windows with the express module to create an HTML page where I need to retrieve data from a server-side function called getfiledata() (I want to keep my Javascript and text file private). I have attempted to use fetch( ...

Using the OR condition in the ternary operator within ReactJS

Recently, I have started working on a ReactJS project focusing on menus. In this project, I have successfully implemented logic for the active menu feature. For instance, when a user is on page 2, the corresponding menu item will be highlighted as active. ...

I am facing an issue where my Javascript hide and show function is not working properly when clicked. Despite not giving

I am currently working on a Javascript onClick function to toggle the visibility of content in a lengthy table. I initially set part of the table's class to display: "none" and added a button to show the hidden content when clicked. However, nothing i ...

Can one obtain a public IP address using Typescript without relying on third-party links?

Though this question has been asked before, I am currently working on an Angular 4 application where I need to retrieve the public IP address of the user's system. I have searched on Stackoverflow for references, but most posts suggest consuming a th ...

Disable the spinner in Angular-Calendar-Year-View component [https://www.npmjs.com/package/angular-calendar-year-view]

I am currently utilizing the angular-calendar plugin, and in order to achieve the Year-View functionality that I need, I have integrated: https://www.npmjs.com/package/angular-calendar-year-view Everything seems to be functioning well, except for an anno ...

Creating dynamic drop-down menus using PHP, HTML, JavaScript, and MySQL

I need help with a form where users are required to select departments and based on that, the corresponding defect fields should populate with matching defects. Currently, when I try removing Defect 4, Defect 3 works; remove 4 & 3, then 2 works and so fo ...

Learn how to prevent two-finger swipe forward/backward on a trackpad using JavaScript or HTML

My app includes a functionality where the URL changes when transitioning from one state to another, for example from home/#state to home/#state2. However, I noticed that when I perform a two-finger swipe using the trackpad from home/#state2, the page navig ...

What is the best way to transmit a JSON object to REST services using Angular?

Whenever I attempt to send the JSON object to REST services, I encounter an error that looks like this: http://localhost:8080/api/v1/cardLimit 400 (Bad Request); JSON Object Example: public class GameLimit implements Serializable { private stati ...

Initiate a jQuery modal dialogue box

As an apprentice with no prior experience working with JavaScript, I encountered a problem with my function that calls a popup. The function works fine on the first button, but fails to work on all subsequent buttons. Since the application keeps adding b ...

Unexpected behavior with async/await in Vues.js

Despite appearing to run correctly, the console log indicates that the final result is being output before the inner await/sync. submitForm: function() { console.log("SUBMIT !"); // vee-validate form validation request const makeVali ...

Setting up a dynamic transition effect with TailwindCSS during page load

One interesting feature I implemented involves a button that, when clicked, makes a div element transparent using a transition effect. To ensure consistency across sessions, I utilized cookies with js-cookie to save and load the visibility state of the el ...

Choose the checkbox by utilizing pre-populated information in Angular 6

I am looking to present a list of roles in checkboxes, where if a role has been previously selected, the checkbox should be pre-checked. Here is the code I am using to return the rolesId: this.Adu.optionId=this.selectedEdit; this.otionService.GetRolesfoO ...

FusionMaps XT integration with VueJs: Troubleshooting connectorClick events issue

I am experiencing some issues with events connectorClick on my VueJS processed map. When I click on the connector line in the example below, the alert function does not seem to work as expected. Vue.use(VueFusionCharts, FusionCharts); let grphMap = new ...

Performance issues are being experienced on website for tablet and smartphone usage due to slow loading times

My client's website is running on an old Dell PowerEdge 2600 with Windows Server 2008. While desktop and laptop access to the site is smooth, access from tablets and smartphones is extremely slow, taking over 10 minutes to load or sometimes not loadin ...

A Vue filtering feature that consistently adds 5 additional elements upon each use

I was wondering, how can I create a computed property filter function that always adds 5 more elements to the current array? Here are more details: Template: <span class="box-content" v-for="item in activeItems" :key="item.id"> <img class=" ...