

Error tracking and monitoring in Next.js
source link: https://dev.to/gogulaanand/error-tracking-and-monitoring-in-next-js-3bje
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.


Error tracking and monitoring in Next.js
Aug 15
・2 min read
Error tracking and performance monitoring is crucial to any application running in production. Simply because we cant expect the end user to report every issue they face and it is our responsibility to proactively check for errors and fix them for better user experience.
With Next.js, it is very easy to setup error tracking in couple of minutes with Sentry
Lets have a look at what Sentry offers:
Main sentry dashboard
Issues dashboard of sentry
We get an overview of all the issues at one place. We can also view release wise report in sentry.
Once, while checking something in my local, some error flashed up during page transition for a second and then disappeared. I couldnt reproduce it again, log was not available in terminal or browser console but it was logged in sentry will full trace ?
Performance dashboard of sentry (similar to chrome light house performance report)
Setup
// install sentry's nextjs sdk
npm install --save @sentry/nextjs
// run setry's setup wizard
// We need to have an sentry account before running
// setup as it will open login window in browser
npx @sentry/wizard -i nextjs
And...
We are done. ?
Now the Sentry SDK will automatically capture unhandled errors and promise rejections, and monitor performance in the client.
We can set up sentry to capture errors in couple of ways.
1.Error object:
try{
aFunctionThatMightFail();
}
catch(err){
throw new Error(err)
}
2.Use Sentry's methods to capture the error:
import * as Sentry from "@sentry/nextjs";
try {
aFunctionThatMightFail();
} catch (err) {
Sentry.captureException(err);
}
Alternatively, we can use React's Error boundary to log the error to Sentry
import * as Sentry from "@sentry/nextjs";
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// we can log error or errorInfo to Sentry here.
// errorInfo will contain the details
// and stack trace which is better for debugging
Sentry.captureException(errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
? We get active support for sentry in nextjs which is a good thing in the long run. ? Next.js v11.1. To explore more, checkout Sentry's guide for nextjs
Credits: Cover Photo by Luke Chesser on Unsplash
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK