All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.commons.utils.exception.GlobalExceptionHandler Maven / Gradle / Ivy

There is a newer version: 1.2.6
Show newest version
package com.github.commons.utils.exception;

import com.github.commons.utils.result.CodeMsg;
import com.github.commons.utils.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartException;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

	private static Logger  logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	@ExceptionHandler(value=Exception.class)
	public Result exceptionHandler(HttpServletRequest request, Exception e){
		logger.error("全局异常:"+e);
		if(e instanceof GlobalException) {
			e.printStackTrace();
			GlobalException ex = (GlobalException)e;
			return Result.error(ex.getCm());
		}else if(e instanceof BindException) {
			BindException ex = (BindException)e;
			List errors = ex.getAllErrors();
			ObjectError error = errors.get(0);
			String msg = error.getDefaultMessage();
			return Result.error(CodeMsg.BIND_ERROR.fillArgs(msg));
		}else if(e instanceof MultipartException){
			e.printStackTrace();
			return Result.error(CodeMsg.INFO(400,"文件上传失败"));
		}else {
			e.printStackTrace();
			return Result.error(CodeMsg.SERVER_ERROR);
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy