SpringBoot项目中的全局异常处理器 Failed to invoke @ExceptionHandler method
文件下载代码
@RequestMapping(value = { "/data/docking/picture/{id}/{empi}" }) public JsonApi picToJSP(@PathVariable String id, @PathVariable("empi") String empi, @Validated({ BaseEntity.SelectOne.class }) TFileWork0 tFileWork0, HttpServletRequest request, HttpServletResponse response) { FileInputStream in; String name = null; Yhxd yhxd = new Yhxd(); yhxd.setEmpi(empi); List<Map<String, Object>> yhxdList = yhxdService.getList(yhxd); if (yhxdList != null && yhxdList.size() > 0) { name = yhxdList.get(0).get("YHMC").toString() + "-心电图-"; } tFileWork0.setId(id); Map<String, Object> map = tFileWork0Service.getOne(tFileWork0); if (map == null) { return new JsonApi(ApiCodeEnum.NOT_FOUND); } else { String url = map.get("file_path").toString() + map.get("file_name"); String na = map.get("file_name").toString(); /*设置文件下載名称*/ String filename = name + na; try { // 图片读取路径 String imgUrl = "C:/Users/chenyan/" + url; in = new FileInputStream(imgUrl); int i = in.available(); byte[] data = new byte[i]; in.read(data); in.close(); response.setContentType("application/octet-stream;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(filename, "UTF-8")); OutputStream outputStream = new BufferedOutputStream(response.getOutputStream()); outputStream.write(data); outputStream.flush(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } return new JsonApi(ApiCodeEnum.OK); } }
全局异常处理器
package com.data.docking.exception; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import com.data.docking.tools.ApiCodeEnum; import com.data.docking.tools.JsonApi; /** * Copyright © 2019 . * * @author: ChenYan * @date: 2019年10月10日 * @description: 全局异常处理器 */ @ControllerAdvice @ResponseBody public class GlobalExceptionHandler { Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(Exception.class) public JsonApi defaultErrorHandler(Exception e) { e.printStackTrace(); log.error("error msg:{}", e.getMessage()); return new JsonApi(ApiCodeEnum.ERROR).setMsg(e.getMessage()); } }
在下载文件的时候报错
只需要把
@ExceptionHandler(Exception.class) 改成 @ExceptionHandler(BindException.class)就可以了。
每件事都需要坚持!