How to log error in catch statement in sentry - javascript

I am new to Sentry and I want to log an error manually.
For some reason I am unable to find in their docs, how I can achieve this
I am using RN project but from their docs, RN extends JS sdk
Consider a function as simple as this
const logErrorIntentionally = () => {
try {
} catch (error) {
//throw sentry error here
}
}
How can I log thrown error in sentry? from my catch block.

According to the docs:
import * as Sentry from '#sentry/browser';
try {
aFunctionThatMightFail();
} catch (err) {
Sentry.captureException(err);
}
For custom messages:
import * as Sentry from '#sentry/browser';
Sentry.captureMessage("Something went wrong");

The most common form of capturing is to capture errors. What can be captured as an error varies by platform. In general, if you have something that looks like an exception, it can be captured. For some SDKs, you can also omit the argument to captureException and Sentry will attempt to capture the current exception. It is also useful for manual reporting of errors or messages to Sentry.
You can read more from the official docs https://docs.sentry.io/platforms/react-native/usage/

Related

How to check if an exception is a FirebaseError / FirebaseAuthError in TypeScript

I'm trying to implement Firebase authentication and user creation on our server, working on TypeScript.
I'm creating a new user, and I have wrapped the whole creation inside a try-catch block. I'm trying to catch several exceptions, one of them being exception thrown by Firebase.
The problem is that I can't check if the exception was thrown by the Firebase, or if it's another type of exception.
Other answers to similar kind of questions suggest to check if the exception is an instance of FirebaseError:
let firebaseUser;
try {
firebaseUser = await firebase.auth().createUser({
email: email,
password: password,
});
// Other code here
} catch (error) {
if(error instanceof FirebaseError){
// handle FirebaseError here
}
}
The problem is, that when there is an error in the createUser function, the error is an instance of FirebaseAuthError, not FirebaseError, so this check fails.
I tried to switch it to FirebaseAuthError and import the FirebaseAuthError as well, but I get an error message:
Package subpath './lib/utils/error' is not defined by "exports" in
\node_modules\firebase-admin\package.json
So what would be the correct way to check that the caught exception is thrown by FirebaseAuth?
I think the best thing you can do, is writing a type guard to ensure your error is a FirebaseAuthError that you will import using import type. I checked, and it seems that it's because the library doesn't export it.
You can freely benefit from the type used by firebase, however, as the module is not listed in the exports, you won't be able to use it at runtime. the import type syntax allows you to still use it during development, but it will be completely ignored at build time.
That means you can't use instanceof FirebaseAuthError as only the type is imported, and you can't use instanceof on something else than a class.
I'm not sure about the following statement, but I guess that every error prefixed by auth/ seem to be a FirebaseAuthError.
Thus, you could write a type guard as follows:
import type { FirebaseAuthError } from 'firebase-admin/lib/utils/error';
function isFirebaseAuthError(error: FirebaseError): error is FirebaseAuthError {
return error.code.startsWith('auth/');
}

Inspecting a caught error in a React Native app

I'm working with a React Native app in a dev environment and am running into an error whereby a toast is shown after I try to upload a file. The code is similar to the following:
function* onUploadPrompt(action: Action): Saga<*> {
try {
yield put(ProfileCertificateUpload.uploadEnd());
} catch (err) {
debugger;
// if upload fails show a toast to user so they may retry
yield put(Toast.showNegative(str.uploadFail()));
yield put(ProfileCertificateUpload.uploadEnd());
}
}
Note that I've set a debugger breakpoint in the catch block. If I stop the package manager and start it again (using yarn start) and go through the flow to trigger the error, I hit the breakpoint:
What puzzles me is that I don't see err anywhere; I can't inspect it. Shouldn't the err error variable be in scope where I set my breakpoint, so that I can have a look at the error and learn more about it?
Instead of debugger, put console.log(‘error:’, err); and check your console to see what the error actually is.

Can I re-create an error object with the original stack and stack frames?

I'm familiar with creating a custom Error object in JavaScript like this.
class CustomError extends Error {
constructor(args) {
super(...args);
Error.captureStackTrace(this, CustomError);
}
}
But given an exception/error that has already been thrown elsewhere I want to create a new error object that is a clone/copy of the original including the stack.
My context is that I'm using a log reporter, e.g. Winston, to capture events and I would like to post error messages to Sentry. Sentry provides a way to capture exceptions like this -
try {
aFunctionThatMightFail();
} catch (err) {
Sentry.captureException(err);
}
The problem though is that Sentry assumes that where the error is captured is where the error was thrown.
One of the benefits of Sentry is that it can report the line numbers of where the error occurred in an app but because I'm aggregating the logs the stack frame from the original error has been lost. I can save additional meta-data which I can send to Sentry but it still highlights the line with Sentry.captureException as the origin of the error and the stack frames from calling Winston.
The Sentry SDK assembles a JSON payload from the Error object you pass to captureException. I think you'll just want to assemble that payload directly and send it using captureEvent. See https://docs.sentry.io/development/sdk-dev/attributes/ for more information.

Writing thrown errors to a file in Javascript

Is there a way to add a default behavior in javascript to the throw event.
Like I am trying to add to a file whenever an error is thrown :
Example :
if (tables.length === 0) {
throw new Error("NO_TABLES_RETRIEVED");
}
I want to write to file first and then throw the error. I know I can add a function and just before throwing I can call that function but just to know more is there something like to add a default behavior with throw?
Error is different from Exception in Javascript w.r.t NodeJS. An error is any instance of the Error class. Errors may be constructed and then passed directly to another function or thrown. When you throw an error, it becomes an exception.2 Here's an example of using an error as an exception:
throw new Error('something bad happened');
but you can just as well create an Error without throwing it:
callback(new Error('something bad happened'));
Since you mentioned in the comment that you don't want to require the error handler file in all the files of the app. You can also make use of NodeJS EventEmitter module or use a error handler middleware
I think your best bet is to use a custom throw. I actually always do it, to be able to write
_throw("MyErrorMessage")
So I would do something like that:
//Should use something like dot-env with the path to your errors
require('dotenv').config()
//I'm just gonna fake it to make it work on your machine:
process.env.error_file_path = './myErrors.txt'
//throwLib.js
const util = require('util')
const fs = require('fs')
const writeFile = util.promisify(fs.appendFile)
_throw = (stringError) => {
writeFile(process.env.error_file_path, "Error : " + stringError + "\n").then(err => {
if (err)
console.log(err)
throw new Error(stringError)
}
)
}
//import this in your files.
//myFile.js
//someStuff
_throw('someMessage1')
_throw('someMessage2')
_throw('someMessage3')
You can create your own custom error and do some logic in the constructor.
function MyError(){
//do some logic herer (e.g. write to file)
console.log("some logic");
}
throw new MyError()
If you are using a NodeJS application, you can centrally manage all your thrown errors.
You should also name your errors:
class ApiError extends Error {
constructor (message, code) {
super(message);
this.name = 'ApiError';
this.code = code;
}
}
Similarly use other names for other error types.
For an express application,
app.use(routes);
// place this after your routes in express app. This will catch all your thrown errors.
app.use(function (err, req, res, next) {
console.log(err);
switch (err.name) {
case 'ApiError':
// write to file here
return res.status(err.code || 500).send({error: err.message});
case 'Some other error':
// handle differently
break;
default:
res.status(err.status || 500).render('500', {error: err});
}
});
Note if you are throwing from within a Promise, async/await, this won't catch your error. You will have to catch them centrally some other way, possibly by catching all Unhandled Promise Rejections in your app
process.on('unhandledRejection', (reason) => {
console.log(reason);
// log error in file
});
Similarly, you should also catch all uncaught exceptions centrally
process.on('uncaughtException', (err) => {
console.log(err);
// log error in file
});
Suggestion:
As far as logging errors in file are concerned, it is a great way to do that only if you're parsing your file by some other way, sending your file to logstash etc.
When you're not planning to parse your file programmatically, log your errors in an errordb / error-table. They are much easier to query that way :)

JS - how to prevent script from stopping after thrown error

How can I prevent the script from stopping after an error has been thrown? Is there something like exception handling in JS?
Console text
Not allowed to load local resource: file:///C:/Users/Temp/image.png
Javascript does have exception handling. There are two possible types of error you can encounter:
1) Places in your application where you proactively guard against errors being thrown, for example, AJAX request. You can handle them like this:
try {
AJAX-code or other code susceptible to errors
} catch(error){
// Log error
}
2) Script errors or compile-time error, for example, undefined variables. In browsers, window.onerror is a global event handler which is called on script or compile errors. However, it's implementation is inconsistent across browsers. You can use it like this:
window.onerror = function(message, url, lineNo) {
// Code to handle the error
}
The main problem with onerror is that no stack trace is passed through which is not very helpful. However, Chromium has added column number and errorObj, so hopefully other browsers will implement the same in near future.
There surely is: try {} catch (exception) {}
Sure, wrap your code inside try/catch:
try
{
//Run some code here
}
catch(err)
{
//Handle errors here
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
You can use a try/catch/finally block to handle errors:
try {
// Whatever you need
} catch(error) {
// Handle error if one occurs
} finally {
// Last resort
}
Note that you can have multiple catch blocks in-between your try and finally as needed.
Here's some more information.

Categories

Resources