package net.geedge.common;

import cn.hutool.log.Log;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 异常处理器
 */
@RestControllerAdvice
public class APIExceptionHandler {

	private static final Log log = Log.get();

	@ExceptionHandler(APIException.class)
	@ResponseStatus(value = HttpStatus.BAD_REQUEST)
	public R handleNZException(APIException e) {
		R r = new R();
		r.put("code", e.getCode());
		r.put("msg", e.getMsg());
		return r;
	}

	@ExceptionHandler(Exception.class)
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	public R handleException(Exception e, HttpServletRequest request) {
		if (e instanceof ClientAbortException) {
			return null;
		}
		log.error(e, "Request uri: {}", request.getRequestURI());
		return R.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
	}
	
}