Skip to content

Commit

Permalink
refactor: exception handling and HTTP response in API
Browse files Browse the repository at this point in the history
  • Loading branch information
cuixiaorui committed Jan 25, 2024
1 parent b7fa402 commit 9f397a8
Show file tree
Hide file tree
Showing 8 changed files with 66 additions and 47 deletions.
23 changes: 14 additions & 9 deletions apps/api/src/app/exception.fliter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,25 @@ import {
HttpException,
} from '@nestjs/common';

import { Request, Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const response = ctx.getResponse();
const status = exception.getStatus();
const message = exception.getResponse() as any;
response.status(status).json({
code: status,
data: null,

const message = exception.message
? exception.message
: `${status >= 500 ? 'Service Error' : 'Client Error'}`;

const errorResponse = {
data: {},
message,
});
code: -1,
};

response.status(status);
response.header('Content-Type', 'application/json; charset=utf-8');
response.send(errorResponse);
}
}
4 changes: 2 additions & 2 deletions apps/api/src/app/transform.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ export class TransformInterceptor implements NestInterceptor {
map((data) => {
return {
data,
code: 200,
message: '',
code: 1,
message: 'Request successful',
};
}),
);
Expand Down
25 changes: 4 additions & 21 deletions apps/client/api/auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { type ErrorVo, isError } from "./common";
import { http } from "./http";

interface LoginDto {
phone: string;
Expand All @@ -17,31 +18,13 @@ interface SignUpDto extends LoginDto {

interface LoginVo {
token: string;
user: UserInfo
user: UserInfo;
}

export async function login(dto: LoginDto) {
const message = useMessage();
const { data } = await useFetchPlus<LoginVo | ErrorVo>("/auth/login", {
body: dto,
method: "post",
});
if (isError(data.value)) {
message.error(data.value.message);
return;
}
return data.value as LoginVo;
return await http.post<LoginVo, LoginVo>("/auth/login", dto);
}

export async function signUp(dto: SignUpDto) {
const message = useMessage();
const { data } = await useFetchPlus<LoginVo | ErrorVo>("/auth/signup", {
body: dto,
method: "post",
});
if (isError(data.value)) {
message.error(data.value.message);
return;
}
return data.value as LoginVo;
return await http.post<LoginVo, LoginVo>("/auth/signup", dto);
}
4 changes: 4 additions & 0 deletions apps/client/api/courses.ts → apps/client/api/course.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,7 @@ export async function fetchCourse(courseId: number) {
export async function fetchNextCourse(courseId: number) {
return await http.get<Course, Course>(`/courses/${courseId}/next`);
}

export async function fetchCourses() {
return await http.get<Course[], Course[]>("/courses");
}
31 changes: 24 additions & 7 deletions apps/client/api/http.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { AxiosInstance, AxiosResponse } from "axios";
import axios from "axios";
import { checkHaveToken, getToken } from "~/utils/token";

const isProd = process.env.NODE_ENV === "production";

Expand All @@ -11,19 +12,35 @@ export const http: AxiosInstance = axios.create({
headers: { "Content-Type": "application/json" },
});

// http.interceptors.request.use((config) => {
// if (checkHaveToken()) config.headers.Authorization = `Bearer ${getToken()}`;
http.interceptors.request.use((config) => {
if (checkHaveToken()) config.headers.Authorization = `Bearer ${getToken()}`;

// return config;
// });
return config;
});

http.interceptors.response.use(
(response: AxiosResponse) => {
const { status, statusText, data } = response;
const { code, message, data } = response.data;

return data;
if (code === 1) {
return data;
} else {
console.error(message);
return Promise.reject(new Error(message));
}
},
(error) => {
// TODO 后面在统一处理
if (error.response.status) {
switch (error.response.status) {
case 400:
console.error(error.message);
break;
case 401:
// TODO 跳转到登录
console.error(error.message, "跳转到登录")
break;
}
return Promise.reject(error);
}
}
);
9 changes: 2 additions & 7 deletions apps/client/pages/Courses.vue
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,9 @@
</template>

<script setup lang="ts">
import { useFetchPlus } from "~/composables/useFetch";
import { fetchCourses } from '~/api/course';
interface Course {
title: string;
id: number;
}
const { data: courses } = await useFetchPlus<Course[]>("/");
const courses = await fetchCourses()
</script>
Expand Down
2 changes: 1 addition & 1 deletion apps/client/store/course.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { defineStore } from "pinia";
import { ref } from "vue";
import { fetchCourse, fetchNextCourse } from "~/api/courses";
import { fetchCourse, fetchNextCourse } from "~/api/course";

interface Statement {
id: number;
Expand Down
15 changes: 15 additions & 0 deletions apps/client/utils/token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export function getToken() {
return localStorage.getItem('token')
}

export function checkHaveToken() {
return getToken()
}

export function setToken(token: string) {
localStorage.setItem('token', token)
}

export function cleanToken() {
localStorage.removeItem('token')
}

0 comments on commit 9f397a8

Please sign in to comment.