I’m currently designing a multi-layered application and am trying to figure out the best practice for error handling within the Business Logic Layer (BLL).
- Should I handle errors directly within the BLL, or is it better to let them propagate up to the presentation layer?
- What are the implications of either approach on maintainability and code clarity?
- Are there specific strategies or patterns (like using custom exceptions or a centralized error handling mechanism) that you would recommend for managing errors in the BLL?
I have tried to create custom errors and throw them when something goes wrong in my business logic
like this
<code>const problemWithSameTitle = await this.getByTitle(problemData.title);
if (problemWithSameTitle) {
throw new ProblemWithSameTitleExists("Problem with the same Title already exists");
}
const createdProblem = await prisma.problem.create({
data: problemData
});
return createdProblem;
</code>
<code>const problemWithSameTitle = await this.getByTitle(problemData.title);
if (problemWithSameTitle) {
throw new ProblemWithSameTitleExists("Problem with the same Title already exists");
}
const createdProblem = await prisma.problem.create({
data: problemData
});
return createdProblem;
</code>
const problemWithSameTitle = await this.getByTitle(problemData.title);
if (problemWithSameTitle) {
throw new ProblemWithSameTitleExists("Problem with the same Title already exists");
}
const createdProblem = await prisma.problem.create({
data: problemData
});
return createdProblem;
and handling it in the controller like this
<code>try {
const problem = await this.problemsService.create(req.body);
const mappedProblem = new ProblemDto(problem);
res.status(201).json(new BaseResponseDto(true, 'Problem created successfully', mappedProblem));
} catch (error) {
if (error instanceof ProblemWithSameTitleExists) {
res.status(400).json(new BaseResponseDto(false, error.message, null));
}
}
</code>
<code>try {
const problem = await this.problemsService.create(req.body);
const mappedProblem = new ProblemDto(problem);
res.status(201).json(new BaseResponseDto(true, 'Problem created successfully', mappedProblem));
} catch (error) {
if (error instanceof ProblemWithSameTitleExists) {
res.status(400).json(new BaseResponseDto(false, error.message, null));
}
}
</code>
try {
const problem = await this.problemsService.create(req.body);
const mappedProblem = new ProblemDto(problem);
res.status(201).json(new BaseResponseDto(true, 'Problem created successfully', mappedProblem));
} catch (error) {
if (error instanceof ProblemWithSameTitleExists) {
res.status(400).json(new BaseResponseDto(false, error.message, null));
}
}