@ControllerAdvice 全局异常处理

自古美人都是妖i 提交于 2019-12-09 13:51:49

使用@ControllerAdvice 定义 全局异常处理

 

package com.app;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

/**
 * ContorllerAdvice 最常见的使用场景是全局异常处理
 * 一般搭配 @ExceptionHandler @ModelAttribute 以及 @InitBinder 使用
 * 如下是, 当单个文件超出最大size时 对应的自定义处理方法
 * 
 *  <p>By default the methods in an {@code @ControllerAdvice} apply globally to
 * all Controllers.
 * 
 * spring:
  servlet:
    multipart:
      max-file-size: 50KB  
 *
 */
@ControllerAdvice
public class CustomExceptionHandler {

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public void uploadException(MaxUploadSizeExceededException e, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/html;charset=utf-8");
    PrintWriter out = resp.getWriter();
    out.write("文件大小超出限制!");
    out.flush();
    out.close();
    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!