ADD file via upload

main
pm4c6ia2v 4 months ago
parent 9778eebc31
commit f0e7beba9b

@ -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;
}
}
Loading…
Cancel
Save