从Java的角度来看,使用异常来处理预期的结果是错误的(异常应该被称为异常)。
对于我的所有服务,我创建了包装器机制,它基本上给出了失败的细节,如果发生这种情况(所有返回都是任意的Result<?>
)。现在,我需要在某些弹出窗口中在客户端浏览器上显示这条消息。
HttpClient实际上支持捕获http响应错误:https://angular.io/guide/http#error-handling
这是从服务器到客户端报告错误的可行方法吗?
是否有一种角度的方法来定义一些从后端API中分离响应的提取器?
假设我会让我的REST返回主体:
{
messageType: "", // Success, Failure, Warning
message: "Message",
content: {
...
}
}
这样,我就可以在拦截器中剥离message, messageType
,在弹出窗口中显示它们,并且只将content
进一步作为主体传递?
发布于 2018-12-30 03:43:47
既然我是从纯Java后端进入web的-- JAVA中的异常是不好的(一般来说),那么为什么在使用HTTP时遵循同样的错误实践(使用错误作为信息)?再读几遍之后,我可以说-除非这实际上是个错误,例如:
这是我的Result<?>
系统的角部分。
拦截器:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Globals } from '../globals.service';
@Injectable()
export class PopupInterceptor implements HttpInterceptor {
constructor(private globals: Globals) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.url.startsWith(this.globals.apiHost)) {
return next.handle(req)
.pipe(
map(e => {
if (e instanceof HttpResponse) {
const response = <Response>e.body;
// use response to do whatever - I am injecting popup service and pushing response.message there for display in component.
return e.clone({ body: response.result });
}
})
);
}
return next.handle(req);
}
}
interface Response {
type: string;
message: string;
result: any;
}
globals.service:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class Globals {
apiHost = '/api/';
}
app.module:
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: PopupInterceptor, multi: true }
],
发布于 2018-12-29 21:37:25
一种使用@ControllerAdvice在服务端捕获所有异常的好方法,并将特定于用户/特性的异常与预期的异常消息和标准结构中的状态代码一起抛出,这样前端就可以有一个异常控制器来动态地在弹出消息中对来自服务的任何消息评估该异常消息。
https://stackoverflow.com/questions/53972370
复制相似问题