我必须为不同的前端(客户端)创建不同的错误响应。现在我不知道会有多少客户。我想以适当的方式构建这个场景。我有一个像下面这样的原型。这是正确的做法吗?请指导我为这种情况选择合适的设计模式。
接口
IClientErrorResponseBuilder {
getFailureResponse()
}
第一个客户
FirstClientErrorResponseBuilder implements IClientErrorResponseBuilder {
getFailureResponse(e: Exception) {
return {
code: e.code,
message: e.message,
}
}
}
第二个客户
SecondClientErrorResponseBuilder implements IClientErrorResponseBuilder {
getFailureResponse(e: Exception ) {
return {
code: e.code,
message: e.message,
reason: "SOME REASON",
}
}
}
来自控制器
import IClientErrorResponseBuilder;
// When instantiated, it will resolve dependency for ErrorResponseBuilder
class FirstController {
private errorBuilder;
constructor(errorBuilder: IClientErrorResponseBuilder) {
this.errorBuilder = errorBuilder;
}
public handler() {
try {
// do the stuffs
}catch(e) {
// If error
this.errorBuilder.getFailureResponse(e);
}
}
}
//实例化时,它将解析ErrorResponseBuilder的依赖关系
class SecondController {
private errorBuilder;
constructor(errorBuilder: IClientErrorResponseBuilder) {
this.errorBuilder = errorBuilder;
}
public handler() {
try {
// do the stuffs
}catch(e) {
// If error
this.errorBuilder.getFailureResponse(e);
}
}
}