springboot處理全域性異常註釋@RestControllerAdvice

1。編寫全域性異常處理類,在類前面加上註釋@RestControllerAdvice,結合@ExceptionHandler一起處理各種對應的異常並返回異常的結果。如下:

package com。lz。hehuorenservice。common。exception;import org。springframework。web。bind。annotation。ExceptionHandler;import org。springframework。web。bind。annotation。RestControllerAdvice;import org。springframework。web。multipart。MultipartException;/** Create by hyhweb on 2021/6/1 19:03 */@RestControllerAdvicepublic class GlobalExceptionHandler {@ExceptionHandler(MultipartException。class)public String MultipartFileExceptionError(MultipartException e) {return “上傳失敗”;}@ExceptionHandler(Exception。class)public String ExceptionError(Exception e) {return “操作失敗”;}}

2。在controller的方法後面加上throws Exception。如下:

package com。lz。hehuorenservice。controller。common;import com。lz。hehuorenservice。common。bean。Project;import io。swagger。annotations。Api;import io。swagger。annotations。ApiOperation;import org。springframework。beans。factory。annotation。Autowired;import org。springframework。web。bind。annotation。PostMapping;import org。springframework。web。bind。annotation。RequestMapping;import org。springframework。web。bind。annotation。RequestParam;import org。springframework。web。bind。annotation。RestController;import org。springframework。web。multipart。MultipartFile;import java。nio。file。Files;import java。nio。file。Path;import java。nio。file。Paths;/** Create by hyhweb on 2021/6/1 18:01 */@RestController@Api(tags = “上傳介面”)@RequestMapping(“upload”)public class UploadController {@Autowired private Project project;@ApiOperation(“上傳圖片介面”)@PostMapping(“/uploadFile”)public String upload(@RequestParam(“file”) MultipartFile file) throws Exception {if (file。isEmpty()) {return “請選擇要上傳的檔案”;}int num = 5 / 0; //丟擲異常測試,會進入全域性異常的方法,正常程式碼不需要這樣寫byte[] bytes = file。getBytes();String fileName = file。getOriginalFilename();Path path = Paths。get(project。getUploadUrl() + fileName);Files。write(path, bytes);return “上傳成功”;}}

備註:

@RestControllerAdvice註釋只處理控制處理器的異常,不會處理控制處理器之前的處理器的異常。