Spring MVC怎么统一异常管理?

1、 在类上加上@ControllerAdvice注解

2、 在方法上加上@ExceptionHandler注解

@ExceptionHandler(Exception.class)

@ResponseBody

public Map<String, String> error(Exception e){

    Map<String, String> errors = new HashMap<>();

    if(e instanceof MaxUploadSizeExceededException || e instanceof SizeLimitExceededException){

       errors.put("message", "文件大小超限,只能上传1m大小文件");

    }else{

       errors.put("message", "内部错误,"+e.getMessage());

    }

    return errors;

}

原文地址:https://www.cnblogs.com/huigee/p/9758289.html