36 lines
789 B
JavaScript
36 lines
789 B
JavaScript
'use strict';
|
|
|
|
const express = require('express');
|
|
const app = express();
|
|
|
|
app.get('/api/p1', p1);
|
|
app.get('/api/p2', p2);
|
|
|
|
app.use(errorHandler); // after request handlers
|
|
|
|
app.listen(3000, () => console.log('Server is running...'));
|
|
|
|
function p1(request, response, next) {
|
|
getData()
|
|
.then(data => response.end('ok: ' + data))
|
|
.catch(error => next(error));
|
|
}
|
|
|
|
function p2(request, response, next) {
|
|
getDataFails()
|
|
.then(data => response.end(data))
|
|
.catch(next);
|
|
}
|
|
|
|
function errorHandler(error, request, response, next) { // there must be 4 arguments
|
|
response.status(500).send('error: ' + error.toString());
|
|
}
|
|
|
|
function getData() {
|
|
return Promise.resolve('some data');
|
|
}
|
|
|
|
function getDataFails() {
|
|
return Promise.reject('some error');
|
|
}
|