From f0e7beba9b10fef200c6759f597a52ca905d8657 Mon Sep 17 00:00:00 2001 From: pm4c6ia2v <3079754565@qq.com> Date: Sat, 1 Nov 2025 22:42:00 +0800 Subject: [PATCH] ADD file via upload --- ExceptionHandler.java | 90 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 ExceptionHandler.java diff --git a/ExceptionHandler.java b/ExceptionHandler.java new file mode 100644 index 0000000..b91218e --- /dev/null +++ b/ExceptionHandler.java @@ -0,0 +1,90 @@ +package com.student.utils; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +/** + * 异常处理工具类,用于统一处理系统中的异常情况 + * 提供异常信息格式化和日志记录功能 + */ +public class ExceptionHandler { + private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + /** + * 处理异常并返回格式化的异常信息 + * @param e 异常对象 + * @return 格式化的异常信息 + */ + public static String handleException(Exception e) { + StringBuilder message = new StringBuilder(); + message.append("[错误] ") + .append(getCurrentTime()) + .append(" - ") + .append(e.getClass().getSimpleName()) + .append(": ") + .append(e.getMessage()) + .append("\n"); + + // 添加异常堆栈信息 + message.append("异常堆栈:\n") + .append(getStackTraceAsString(e)); + + // 记录到控制台 + System.err.println(message.toString()); + + // 这里可以扩展为写入日志文件 + // logToFile(message.toString()); + + return e.getMessage(); // 返回简洁的错误信息给用户 + } + + /** + * 获取当前时间的格式化字符串 + * @return 当前时间字符串 + */ + private static String getCurrentTime() { + return LocalDateTime.now().format(formatter); + } + + /** + * 将异常堆栈转换为字符串 + * @param e 异常对象 + * @return 异常堆栈字符串 + */ + private static String getStackTraceAsString(Exception e) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + e.printStackTrace(pw); + pw.close(); + return sw.toString(); + } + + /** + * 验证学生ID格式 + * @param id 学生ID + * @return 是否有效 + */ + public static boolean isValidStudentId(String id) { + return id != null && !id.trim().isEmpty(); + } + + /** + * 验证学生姓名格式 + * @param name 学生姓名 + * @return 是否有效 + */ + public static boolean isValidStudentName(String name) { + return name != null && !name.trim().isEmpty() && name.length() <= 20; + } + + /** + * 验证学生年龄 + * @param age 学生年龄 + * @return 是否有效 + */ + public static boolean isValidStudentAge(int age) { + return age >= 1 && age <= 150; + } +} \ No newline at end of file