Error Logging with Custom Logger
Set up a custom logger function in Next.js to record errors in an external logging service whenever an error occurs in the application.
import axios from 'axios';
export const logError = async (error) => {
// Replace this URL with the endpoint of your external logging service
const loggingServiceUrl = 'https://your-external-logging-service.com/log';
try {
// Send error information to the logging service
await axios.post(loggingServiceUrl, {
timestamp: new Date().toISOString(),
message: error.message,
stack: error.stack,
});
console.error('Error logged to external service:', error);
} catch (loggingError) {
// In case logging also fails
console.error('Failed to log error to external service:', loggingError);
}
};
Defines an asynchronous function logError that sends error details to an external logging service using axios HTTP client. The error object is expected to contain message and stack properties. If logging fails, it logs the failure to the console.
import React from 'react';
import { logError } from './logger'; // Assume logger.js exports logError
class ErrorBoundary extends React.Component {
componentDidCatch(error, errorInfo) {
// Handle the error and errorInfo
logError(error);
// You can also log errorInfo if needed
}
render() {
if (this.state.hasError) {
// You can render any fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
This React component acts as an error boundary within your Next.js application. It utilizes componentDidCatch to catch errors in its child component tree, calls the logError function to send these errors to your external service, and provides fallback UI if an error occurs.
import React from 'react';
import ErrorBoundary from './ErrorBoundary'; // ErrorBoundary from the previous snippet
export default function MyApp({ Component, pageProps }) {
return (
<ErrorBoundary>
<Component {...pageProps} />
</ErrorBoundary>
);
}
This is a custom _app.js file for a Next.js application. It wraps the entire application in the ErrorBoundary component to catch any unhandled errors in the application's component tree.
/* Include this CSS in your global styles or a component's module.css */
/* Style for error fallback UI */
h1 {
color: red;
font-size: 24px;
}
CSS to style the fallback UI error message, changing the text color to red and setting a font-size. This should be included in your global CSS file or a module CSS file where the ErrorBoundary is used.