Commit 5cdac6e6 authored by wudizhanche1000's avatar wudizhanche1000

将错误用Error对象传到前端

parent db696688
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import App from '../models/browserapp'; import App from '../models/browserapp';
import {Http, RequestOptions, Headers} from '@angular/http'; import {Http, RequestOptions, Headers, Response} from '@angular/http';
import 'rxjs/add/operator/toPromise'; import 'rxjs/add/operator/toPromise';
import {Observable} from 'rxjs/Rx';
/** /**
* Created by weijian on 2016/12/30. * Created by weijian on 2016/12/30.
*/ */
...@@ -19,10 +20,24 @@ export class AppService { ...@@ -19,10 +20,24 @@ export class AppService {
return this.http.get(`http://localhost:8000/apps/${id}`).map((response) => new App(response.json())).toPromise(); return this.http.get(`http://localhost:8000/apps/${id}`).map((response) => new App(response.json())).toPromise();
} }
handleError(error: Response | any) {
// In a real world app, we might use a remote logging infrastructure
let err: Error;
if (error instanceof Response) {
err = error.json() || {};
} else {
err = new Error('Unknown Error');
}
return Observable.throw(err);
}
save(app: App): Promise<any> { save(app: App): Promise<any> {
let headers = new Headers({'Content-Type': 'application/json'}); let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers}); let options = new RequestOptions({headers: headers});
return this.http.post(`http://localhost:8000/apps/${app.id}`, app, options).map((response) => response.json()).toPromise(); return this.http.post(`http://localhost:8000/apps/${app.id}`, app, options)
.map((response) => response.json())
.catch(this.handleError)
.toPromise();
} }
update(app: App) { update(app: App) {
......
...@@ -19,5 +19,9 @@ export class BadRequest extends KoaError { ...@@ -19,5 +19,9 @@ export class BadRequest extends KoaError {
super(msg, 400); super(msg, 400);
} }
} }
export const InternalError = new KoaError(STATUS_CODES[500], 500); export class InternalError extends KoaError {
constructor(public error: Error) {
super(STATUS_CODES[500], 500);
}
}
...@@ -28,7 +28,7 @@ export class App extends Model { ...@@ -28,7 +28,7 @@ export class App extends Model {
async checkExists() { async checkExists() {
let app = await App.findOne({id: this.id}); let app = await App.findOne({id: this.id});
if (app) { if (app) {
throw new ModelExistsError(this.id); throw new ModelExistsError(`App ${this.id} exists`);
} }
} }
......
import {KoaError} from '../koa/errors';
/** /**
* Created by weijian on 2017/1/4. * Created by weijian on 2017/1/4.
*/ */
class ModelError extends Error { export abstract class ModelError extends KoaError {
constructor(msg: string) { abstract errCode: string;
super(msg);
constructor(msg: string, status: number) {
super(msg, status);
} }
} }
export class ModelExistsError extends Error { export class ModelExistsError extends ModelError {
constructor(id: string) { errCode: string = 'ERROR_MODULE_EXISTS';
super(`App ${id} already exists`);
constructor(msg: string) {
super(msg, 400);
} }
} }
...@@ -5,7 +5,7 @@ import Router = require('koa-router'); ...@@ -5,7 +5,7 @@ import Router = require('koa-router');
import {NotFound, BadRequest, InternalError} from '../koa/errors'; import {NotFound, BadRequest, InternalError} from '../koa/errors';
import {Model} from '../db/mongo'; import {Model} from '../db/mongo';
import {App} from '../models/app'; import {App} from '../models/app';
import {ModelExistsError} from '../models/errors'; import {ModelExistsError, ModelError} from '../models/errors';
const router = new Router(); const router = new Router();
router.get('/apps', async(ctx, next) => { router.get('/apps', async(ctx, next) => {
...@@ -26,10 +26,10 @@ router.post('/apps/:id', async(ctx, next) => { ...@@ -26,10 +26,10 @@ router.post('/apps/:id', async(ctx, next) => {
try { try {
ctx.body = await app.save(); ctx.body = await app.save();
} catch (e) { } catch (e) {
if (e instanceof ModelExistsError) { if (e instanceof ModelError) {
throw new BadRequest(`App ${ctx.params.id} already exists`); throw e;
} else { } else {
throw InternalError; throw new InternalError(e);
} }
} }
}); });
......
...@@ -28,8 +28,11 @@ app.use(async(ctx, next) => { ...@@ -28,8 +28,11 @@ app.use(async(ctx, next) => {
// will only respond with JSON // will only respond with JSON
ctx.status = err.status || 500; ctx.status = err.status || 500;
ctx.body = { ctx.body = {
message: err.message message: err.message,
}; };
if (err.errCode) {
ctx.body['errCode'] = err.errCode;
}
if (ctx.response.status >= 400) { if (ctx.response.status >= 400) {
logger.warn(err); logger.warn(err);
} else if (ctx.response.status >= 500) { } else if (ctx.response.status >= 500) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment