|
| 1 | +/** |
| 2 | + * Copyright 2017, Google, Inc. |
| 3 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | + * you may not use this file except in compliance with the License. |
| 5 | + * You may obtain a copy of the License at |
| 6 | + * |
| 7 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + * |
| 9 | + * Unless required by applicable law or agreed to in writing, software |
| 10 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | + * See the License for the specific language governing permissions and |
| 13 | + * limitations under the License. |
| 14 | + */ |
| 15 | + |
| 16 | +// sample-metadata: |
| 17 | +// title: Express integration |
| 18 | +// description: Starts and Express service with integrated error reporting. |
| 19 | +// usage: node express.js |
| 20 | + |
| 21 | +'use strict'; |
| 22 | + |
| 23 | +function express() { |
| 24 | + // [START error_reporting_express] |
| 25 | + // [START error_reporting_setup_nodejs_express] |
| 26 | + const express = require('express'); |
| 27 | + |
| 28 | + // Imports the Google Cloud client library |
| 29 | + const {ErrorReporting} = require('@google-cloud/error-reporting'); |
| 30 | + |
| 31 | + // Instantiates a client |
| 32 | + const errors = new ErrorReporting(); |
| 33 | + |
| 34 | + const app = express(); |
| 35 | + |
| 36 | + app.get('/error', (req, res, next) => { |
| 37 | + res.send('Something broke!'); |
| 38 | + next(new Error('Custom error message')); |
| 39 | + }); |
| 40 | + |
| 41 | + app.get('/exception', () => { |
| 42 | + JSON.parse('{"malformedJson": true'); |
| 43 | + }); |
| 44 | + |
| 45 | + // Note that express error handling middleware should be attached after all |
| 46 | + // the other routes and use() calls. See the Express.js docs. |
| 47 | + app.use(errors.express); |
| 48 | + |
| 49 | + const PORT = process.env.PORT || 8080; |
| 50 | + app.listen(PORT, () => { |
| 51 | + console.log(`App listening on port ${PORT}`); |
| 52 | + console.log('Press Ctrl+C to quit.'); |
| 53 | + }); |
| 54 | + // [END error_reporting_setup_nodejs_express] |
| 55 | + // [END error_reporting_express] |
| 56 | +} |
| 57 | +express(); |
0 commit comments