Throwing custom exception in React - reactjs

So I have this function which sends request to the API and I want to throw exception when requests fails:
async function getCampaigns() {
try {
const response = await api.get('/cars');
setSelectItems(
response.map((item: Car) => ({
label: item.carLabel,
value: item.carValue
}))
);
setLoading(false);
} catch (error: any) {
const exception = new Exception(error);
exception.kind = 'recoverable';
throw exception;
}
}
I created custom exception to handle errors in this code:
Exception.ts
type ExceptionType = 'nonrecoverable' | 'recoverable';
export class Exception extends Error {
public kind: ExceptionType;
constructor(message?: string, options?: ErrorOptions) {
super(message, options);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, Exception);
}
this.kind = 'nonrecoverable';
this.name = 'Exception';
}
}
However I am getting the following error whenever I get error response:
Unhandled Runtime Error
Exception: AxiosError: Request failed with status code 401
which is pointing at this line:
const exception = new Exception(error);
Not sure why is this happening and how can I throw the custom error like this?
EDIT:
So the actual problem here is that, when I catch the error and throw custom one based on the error caught I throw it again in the catch block. I think this results in the custom error that is being thrown uncaught.
And because the custom error is uncaught, in Next.js development mode I get this error Overlay telling me about unhandled error...
Even though I have ErrorBoundary component that works as inteded (so redirects to the error component) but still Next.js overlay is displayed. So I am not sure how should I handle the custom error inside catch block in this situation? Is this correct approach already and should I leave it as it is or is there some better wayt to do this?

Related

React: Unhandled Rejection : Cannot read property 'data' of undefined

I have sign up page and when user press the button got some errors if there are any. But when inputs are correct and there is no errors, i got an another error:
Unhandled Rejection (TypeError): Cannot read property 'data' of undefined
Heres my code:
try {
const response = await signup(body);
push('/login');
} catch (error){
if (error.response.data.validationErrors) {
setErrors(error.response.data.validationErrors);
}
}
try {
const response = await signup(body);
push('/login');
} catch (error){
if (error?.response?.data?.validationErrors) {
setErrors(error?.response?.data?.validationErrors);
}
}
please try this as the condition does not getting data from the response so you can use the fallback
I think there is no object called "data" in your response. Try to log your response and see whether there is an object called "data".

Apollo error handling in one point in application

I would like to add error handling in my apollo react app. I'm checking error
export enum ERROR_CODES {
ERROR_USER_NOT_EXIST = "ERROR_USER_NOT_EXIST"
}
export const getErrorMessage = (error: string): string | null => {
switch(error) {
case ERROR_CODES.ERROR_USER_NOT_EXIST:
return 'test error';
default:
return null;
}
}
and I want to show snackBar for errors which I have in switch case.
I understand that i can't do it with apollo-link-error because i want to show an error like react component and I don't want to add error handling for each query request in my components. Maybe exist way to do it in one point in my app and without apollo-link-error.
Use apollo-link-error ;)
Nobody forces you to only console.log() error or break a data flow. You can use it to "inject your hook" only, to be notified on errors.
You can wrap your app in some context provider - create a 'communication channel' - use it to write errors (from error link) and to render (read and clear) them in snackBar.

How to handle error code with message in react

In angular we have something like mport {HttpClient, HttpErrorResponse, HttpHeaders} from "#angular/common/http";
so when we make a post call using http and Rxjs,like below code..we have something called ErrorEvent.
private runBuild(jobName: string, payload: string) {
return this.http.post(this.jenkinsURLs.runJobUrl(jobName), "json=" + encodeURIComponent(payload), httpOptions)
.pipe(catchError(this.handleError));
};
private handleError(error: HttpErrorResponse) {
let errorMessage: string = '';
***if (error.error instanceof ErrorEvent) {
errorMessage = 'An error occurred: ' + error.error.message;
} else {
errorMessage = `Jenkins returned code ${error.status}, body was: ${error.message}`;
}***
return throwError(errorMessage);
};
but in react, if I want to have different messages for different error codes, I have to do it manually because we don't have something like ErrorEvent.
COuld you please suggest any generic way to have some sort of ErrorEvent so that I can assign different message by validating the instanceOf operator in react
You can wrap < App /> (or at another relevant place to wrap just once) with < ErrorBoundary > that will be trigger to do something at componentDidCatch lifeCycle. {((error, errorInfo)} params at this lifeCycle can be the handlers of the fit error that suppose to be shown - https://reactjs.org/docs/error-boundaries.html

unable to catch errors in react-native

How Can I handle error in React-Native
So this is my error enums
export const frontendErrors = {
INVALID_PHONE_NUMBER_ENTERED: 'Sorry you have entered invalid phone number'
}
From my phoneAuth.js file, I am throwing error in catch statement like this
catch (err) {
const errorSearch = 'auth/invalid-phone-number'
if (err.message.includes(errorSearch)) {
throw new Error(frontendErrors.INVALID_PHONE_NUMBER_ENTERED)
}
And When I catching the error in the parent component
catch (error) {
console.log(error)
this.dropDownAlertRef.alertWithType('error', 'Error', error)
}
in the log I am getting my error as an object and like this
Error: Sorry you have entered invalid phone number
The dropdownAlertRef takes in string so it is logging an empty object i.e.
this.dropDownAlertRef.alertWithType('error', 'Error', 'Invalid phone number')
this will log error.
What have I tried?
Doing, console.log(error.Error) gives undefined. How can I access my error?
You can do something like this.
console.log(error.message)
For more refrence you can refer here

React error overlay - show for one error then throw a different one for calling code to handle

I currently have a react app where there are some async functions dealing with redux actions. All these actions are wrapped in this Act function to ensure that any unexpected errors are logged and a more user friendly error is sent to the UI code which then displays it to the user.
export function Act<R>(
callback: (dispatch: Dispatch, getState: () => ReduxState) => Promise<R>
): typeof callback {
return async (dispatch, getState) => {
try {
// if the callback works fine, just return it's value
return await callback(dispatch, getState);
} catch (e) {
if (e instanceof UserError) {
// we are expecting the action to throw these, although should still be logged
console.log(`async callback threw user error: ${e}`);
// propogate to UI code.
throw e;
} else {
// Some exception happened that wasn't expected, log a traceback of the error
console.trace(`Error in Async Action: ${e}`);
// HERE IS WHERE I WANT TO IMPROVE ^
// since the error thrown will likely be shown to the user just show a generic message
throw new UserError('something went wrong');
}
}
};
}
This is working fine although sometimes console.trace isn't enough for me to realize something went wrong that I wasn't expecting, either because the error never makes it's way to the UI or
What I would really like to do is when an unexpected error is thrown in these actions and dev mode is on it would show the error overlay that would be shown if this was a floating promise
I tried using reportRuntimeError from react-error-overlay but I obviously didn't import it correctly since it was logged as undefined:
import { reportRuntimeError } from 'react-error-overlay'; // didn't work and couldn't find type definitions for the module
I tried npm install #types/react-error-overlay which wasn't able to find type definitions for that module and I'm not clear on whether that is the right place to even be trying to do this.
Is there a way to show the error that was originally thrown and then return a different one to be handled by the UI code?
Realized about half way through writing my question that React shows the overlay for Promises that throw an error that are never handled, so I just had to make a promise that happens to throw the error I want to show and not handle it anywhere:
else {
// This gets logged as an Unhandled Promise Rejection
// so React will show the overlay for it as well.
void Promise.reject(e);
throw new UserError(fallbackErrorMessage);
}

Resources