异常处理
BaskServer 默认提供了异常处理接口,用于处理API请求中的异常。
package com.basksoft.core;
import com.basksoft.core.servlet.BaskServletResponseWrapper;
import java.io.IOException;
/**
* 异常处理接口,用于自定义API请求的异常处理策略。
* 可通过 {@link AbstractBaskFilter#setExceptionHandler(ExceptionHandler)} 注入自定义实现。
*
* @author William.Jiang
* @since 2026年6月9日
*/
public interface ExceptionHandler {
/**
* 处理异常,将错误信息写入响应。
*
* @param resp 响应包装对象
* @param ex 要处理的异常
* @throws IOException 写入响应时可能抛出
*/
void handle(BaskServletResponseWrapper resp, Exception ex) throws IOException;
}
默认的异常处理接口实现类为 {@link DefaultExceptionHandler},该实现类将异常信息写入响应,并返回HTTP状态码500。 你可以通过实现该接口来自定义异常处理策略。 参考示例:
public class MyExceptionHandler implements ExceptionHandler {
private static final ObjectMapper mapper;
static {
Builder builder = JsonMapper.builder();
builder.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper = builder.build();
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
SimpleModule module = new SimpleModule();
module.addSerializer(new BigDecimalJsonSerializer());
module.addSerializer(new LocalDateJsonSerializer());
module.addSerializer(new LocalTimeJsonSerializer());
module.addSerializer(new LocalDateTimeJsonSerializer());
mapper.registerModule(module);
}
@Override
public void handle(BaskServletResponseWrapper resp, Exception ex) throws IOException {
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
Map<String, Object> map = new HashMap<>();
map.put("errorMsg", ex.getMessage());
try (OutputStream out = resp.getOutputStream()) {
mapper.writeValue(out, map);
out.flush();
} catch (IOException e) {
throw new BaskException(e);
}
}
}
创建自定义异常处理类后,将异常处理类注入到BaskServer中,即可实现自定义异常处理策略。
示例代码:
@Bean
public FilterRegistrationBean<BaskFilter> registerReportFilter() {
FilterRegistrationBean<BaskFilter> registration = new FilterRegistrationBean<>(new BaskFilter());
registration.getFilter().setExceptionHandler(new MyExceptionHandler());
registration.addUrlPatterns("/baskserver/*");
registration.setName("bask");
registration.setOrder(1);
return registration;
}